Skip to content
Advertisement

is_page and query_posts not working correctly

For some reason the following code is displaying both types of posts instead of just the specified post using query_posts. I am not quite sure what is going on, but it appears that the loop is ignoring my condition of is_page('news') or is_page('othernews'). Does anyone have an idea why this might be the case?

<?php 
    if (is_page('news')) :
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        query_posts('news');
    endif;

    if (is_page('othernews')) :
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        query_posts('my-other-news'); ?>
    endif;

    while (have_posts()) : the_post();
        get_template_part( 'part-post');
    endwhile;
?>

Advertisement

Answer

Try this whether this works for you,

<?php 
    if (is_page('news')) :
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $query = WP_query(array('post_type' => 'news')); 
    else if (is_page('othernews')) :
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
       $query = WP_query(array('post_type' => 'other-news')); 
    else 
        $query = WP_query(array('post_type' => 'post')); 
    endif;

    while ($query->have_posts()) : $query->the_post();
        get_template_part( 'part-post');
    endwhile;
?>

The last else condition is to handle if none of the first 2 condition satisfies. So you can remove it if you no need that.

Hope this helps you.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement