Site logo

Archived topic

Query loop and current page item

7 replies · Started by Dan on October 18, 2022

Viewing posts 1–8 of 8

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

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 );

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

This archived topic is closed to new replies.