Hello, I'm trying to insert conditional css in wp_head by checking whether a post from a CPT is the most recent one (the latest).
I've tried many different code snippets and none of them worked. Trying to achieve this for regular posts worked, the issue is with MB CPTs. Here's the latest code snippet I'm trying with :
$current_post_id = get_the_ID();
$args = array(
'post_type' => 'projects',
'posts_per_page' => 1,
'post_status' => 'publish',
'order' => 'DESC',
'orderby' => 'date',
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
$query->the_post();
$latest_post_id = get_the_ID();
if ( $current_post_id === $latest_post_id ) {
add_action( 'wp_head', 'latest_post_css' );
} else {
add_action( 'wp_head', 'not_latest_post_css' );
}
wp_reset_postdata();
} else {
// No posts found, trigger the custom action
add_action( 'wp_head', 'latest_post_css' );
}
function not_latest_post_css() {
// Custom function for the not latest post CSS
echo '<style>#main { color: green; }</style>';
}
function latest_post_css() {
// Custom function for the latest post CSS
echo '<style>#main { color: blue; }</style>';
}
the code above always triggers the not_latest_post_css function and shows it everywhere on the site - no matter if I'm browsing a page or a post. So the check isn't performed correctly. Could you please tell me where I'm wrong?
Thanks in advance!