• As I understand it, is_single() will not work with new WP_Query( $args ); If that is the case, how do you check “is_single” with custom queries?

    Thank You

Viewing 2 replies - 1 through 2 (of 2 total)
  • MK

    (@mkarimzada)

    Hi there,

    You could read more about conditional tags here. Remember to hook the wrapper function of is_single after wp_query ran if you are using it in functions.php or give it a priority to run later.

    To do this in template files you could create custom query:
    $query = new WP_Query( array( 'post_type' => 'post' ) );

    You could check the post type in the loop:

    if( $query->have_posts() ) { 
        if( 'post' == $query->post_type ) {
        // Do something with single post
        }
    
        if( 'page' == $query->post_type ) {
        // Do something with single page
        }
    
        if( 'book' == $query->get_post_type() ) {
        // Do something with book post type
        }
    }

    Or you could create a function and give it a higher priority:

    function where_am_i()
    {
        if (is_single()) {
            // Do something with single post
        }
    
        if (is_page()) {
            // Do something with single page
        }
    }
    
    add_action('the_post', 'where_am_i', 135);

    You could create a post object and check by ID:

    function where_am_i($post_ID)
    {
        global $post;
        if ($post->ID == $post_ID) {
            // Do something here
        }
    }
    
    add_action('the_post', 'where_am_i', 135);
    Moderator bcworkz

    (@bcworkz)

    The procedural is_query() only reflects the main query object for the request. But there is also a class method WP_Query::is_single() you can use for new, custom queries.

    $query = new WP_Query( array( 'post_type' => 'post' ) );
    if ( $query->is_single()) {
      //do something?
    }

    This is a bad example because the new query’s arg is not a single sort of arg. Typically with custom queries you’d already know if it’s for a single post or not. None the less, it’s how you would check if a custom query is single or not.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘new WP_Query( $args ) and is_single() Not Working’ is closed to new replies.