Archived topic
Query loop and current page item
7 replies · Started by Dan on October 18, 2022
I have created a query loop which lists all the posts of a CPT in a single CPT template.
Similar to WP core class 'current_page_item' which is added to menu items for example, how can GP query loop add that class to an item when the user is on that same page. I would like to utilize that class for styling the current item in the list.
Image:
https://www.dropbox.com/s/w7uoyp2lzrp8qe1/query-loop-current.jpg?dl=0
Thanks,
Dan
Hi there,
not sure on this, its not as simple as hooking into a PHP loop and checking IDs of current object and current post.
Is it possible to see what you have so far ? Might help getting the grey matter working
Thanks David for your response.
The site is currently on local dev, I'll share once it's online.
But I think it should be a basic functionality similar to the https://developer.wordpress.org/reference/functions/wp_list_pages/ functionality which adds classes to current page/post.
Dan
My first thoughts would to use the post_class filter like so:
function db_current_post_class( $classes, $class, $post_id ) {
global $wp_query;
$current_id = $wp_query->get_queried_object_id();
if( $current_id == $post_id ) {
$classes[] = 'current-page-item';
}
return $classes;
}
add_filter( 'post_class', 'db_current_post_class', 10, 3 );
Thanks David, that worked perfectly.
Question - does this run on all the queries of the site? Should this be a built-in feature of GP's query loop block?
https://www.dropbox.com/s/uhgvyr47r2ib4z1/current-page-item.jpg?dl=0
Dan
So the post_class hook will fire anywhere that uses the get_post_class function.
You should be able to do this and check the post type first:
function db_current_post_class( $classes, $class, $post_id ) {
if ( 'your-post-type' == get_post_type() ) {
global $wp_query;
$current_id = $wp_query->get_queried_object_id();
if( $current_id == $post_id ) {
$classes[] = 'current-page-item';
}
}
return $classes;
}
add_filter( 'post_class', 'db_current_post_class', 10, 3 );
Adding it to the Query Loop, could be something we could add. I'll raise an issue on it
Great, thanks for your support!
Dan
You're welcome