This is for a Wordpress site with historical data. Custom post types exist, one of historical figures ('people
') and events ('events
').
When an internal link placed in a regular post's content, I would like for the link to automatically change colour depending on which post type it links to. For example:
"History is filled with many people and events. [Henry VIII] was once [born]."
The link "Henry VIII" should be red as it links to a post in 'people
', and "born" would be green as it links to a post in 'events
'.
Is this possible?
Unable to set css for specific links; it's all or nothing. Conducted a web search for any solution. None found.
This is for a Wordpress site with historical data. Custom post types exist, one of historical figures ('people
') and events ('events
').
When an internal link placed in a regular post's content, I would like for the link to automatically change colour depending on which post type it links to. For example:
"History is filled with many people and events. [Henry VIII] was once [born]."
The link "Henry VIII" should be red as it links to a post in 'people
', and "born" would be green as it links to a post in 'events
'.
Is this possible?
Unable to set css for specific links; it's all or nothing. Conducted a web search for any solution. None found.
Share Improve this question asked Feb 15 at 17:03 James E.James E. 1 New contributor James E. is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 2 |1 Answer
Reset to default 0I would suggest you dynamically add CSS classes based on the post type the link points to. Here are the steps to do it :
1- Add javascript something like :
jQuery(document).ready(function ($) {
$("a").each(function () {
var link = $(this);
var url = link.attr("href");
// Ensure it's an internal link
if (url && url.startsWith(window.location.origin)) {
$.ajax({
type: "POST",
url: ajaxData.ajaxurl,
data: {
action: "get_post_type",
url: url
},
success: function (response) {
if (response.type === "people") {
link.addClass("link-people");
} else if (response.type === "events") {
link.addClass("link-events");
}
}
});
}
});
});
2- Add ajax code in functions.php like this :
function get_post_type_by_url() {
if (isset($_POST['url'])) {
$post_id = url_to_postid($_POST['url']);
if ($post_id) {
$post_type = get_post_type($post_id);
wp_send_json(array('type' => $post_type));
}
}
wp_send_json(array('type' => ''));
}
add_action('wp_ajax_get_post_type', 'get_post_type_by_url');
add_action('wp_ajax_nopriv_get_post_type', 'get_post_type_by_url');
3- Add css
.link-people {
color: red !important;
}
.link-events {
color: green !important;
}
a[href*="/event/"] { color : red; }
– mmm Commented Feb 15 at 17:09