doujiao1949 2014-07-19 21:31
浏览 38
已采纳

对于所有链接,使用JS或PHP-Wordpress添加css以切换基于Post Type的链接颜色

I'm not sure what route to start down or what would be the appropriate way to do what I'm trying to accomplish here. Whether it's possible to do in PHP, or how to do it in JS, any help is greatly appreciated.

For each link found on a page, (possibly found within widgets,theme's template pages, forums, etc.), how do I search and find out the post_type and then append a specific link color for that particular type?


So for example:

For a list of recent posts in a sidebar widget
(here is the best way I can describe the code intentions):

For each post_type, dynamically set the following
'post'= color:black, 
'project' = color:dark blue,  
'topics' = color:dark green, 
and so on.

Additionally, if there is a link to another post anywhere else in the site, such as in another post's body content or even a forum topic, I need to append a class to that link. Then my CSS can be something along the lines of

.forum-post-link{color: #006400;}
.project-post-link{color: #00008B;}
.standard-post-link{color:#000;}
  • 写回答

1条回答 默认 最新

  • dqby43944 2014-07-21 00:15
    关注

    Here's a solution that should work off the shelf. You may need to adjust the selector a bit to avoid main site navigation links.

    An anchor <a> with an href automatically has numerous properties such as hostname , pathname , origin etc that relate to various parts of the url. Following uses these properties to isolate links that are external ( not same domain ) and also find the home page links.

    It should be fairly easy to adapt to live site based on comments within as well as extend for more than the 3 main routes mentioned in question.

    /* set according to site domain */
    var siteHost = "myurl.com";
    
    var linkClasses = {
        /* adjust string values as classes to suit css rules, keys match term to look for in url */
        post: 'post',
        forum: 'forum',
        project: 'project'
    }
    
    $('a').each(function () {
    
        var host = this.hostname; /* returns domain.com */
        if (host !== siteHost) {
            return; /* not a local link, quit here */
        }
        var newClass = '';
        var path = this.pathname; /* returns eveything after http://myurl.com  */
    
        if (path && path !== '/') {
            /* we only want to look at first part of path*/
            var mainPath = path.split('/')[1];
            /* now check all the various terms in linkClasses object */ 
            $.each(linkClasses, function (key, value) {
                if (mainPath.indexOf(key) > -1) {
                    newClass = linkClasses[key];
                }
            });
    
            $(this).addClass(newClass);
        } else {
            /* is home page link */
            $(this).addClass('home'); /* to test home page link finding ability */
        }
    });
    

    <kbd>DEMO</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?