对于所有链接,使用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;}
我不确定从哪条路线开始,或者以什么方式做我正在尝试的方法 在这里完成。 无论是用PHP做什么,还是用JS做什么,都非常感谢任何帮助。 p>
对于页面上的每个链接,(可能在小部件中找到, 主题的模板页面,论坛等。) em>,如何搜索并找出post_type,然后为该特定类型附加特定的链接颜色? p>
例如: p>
获取侧栏小部件中最近发布的帖子列表 strong>
此外,如果有 链接到网站中其他任何位置的其他帖子,例如在其他帖子的正文内容甚至是论坛主题中,我需要在该链接中附加一个类。 然后我的CSS可以是 p>
(这是我能描述代码意图的最佳方式): p>
对于每个post_type,动态设置以下
'post'= color:black ,
'project'=颜色:深蓝色,
'topics'=颜色:深绿色,
等等。
code> pre>
.forum-post-link {color:#006400;}
.project-post-link {color:#00008B ;}
.standard-post-link {color:#000;}
code> pre>
div>
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 */
}
});