1
<?php
    $args = array(
        'post_type'=>'weather_today',
        'orderby'=>'ID',
        'order'=>'ASC',
        'posts_per_page'=>1
    );
    $query = new WP_Query($args);
    if ($query->have_posts()) {
        while ( have_posts() ) : the_post();
            the_content();
        endwhile;
    }
    wp_reset_postdata();
?>

Outputs a post content (the_content()) that is not of a weather_today type. Why is this? I checked my SQL, in wp_posts I only have one post of post_type = "weather_today" and it's not the one being outputted. This query is up in my header... and I believe above any other custom queries. Furthermore, it seems the other params are respected, the post I am getting is only 1 and is that last regular post by ID.

So why is the post_type, the most important param in this query, being ignored?

2

Try this

<?php
    $args = array(
        'post_type'=>'weather_today',
        'orderby'=>'ID',
        'order'=>'ASC',
        'posts_per_page'=>1
    );
    $query = new WP_Query( $args );
    while ( $query->have_posts() ) : $query->the_post();

        //loop 

    endwhile;
    wp_reset_postdata();
?>
  • 1
    It makes no sense to use wp_reset_query in this code. You don't modify global $wp_query object... You have to use wp_reset_postdata() though... – Krzysiek Dróżdż Jul 25 '18 at 20:23
  • 1
    oh yes. corrected – Latheesh V M Villa Jul 25 '18 at 21:28
1

The problem with your code is pretty simple... You use your custom $query in if statement, but then you use global $wp_query in while loop...

<?php
    $args = array(
        'post_type'=>'weather_today',
        'orderby'=>'ID',
        'order'=>'ASC',
        'posts_per_page'=>1
    );
    $query = new WP_Query($args);  // <- here you create custom $query
    if ($query->have_posts()) {  // <- here you check if it has any posts
        while ( have_posts() ) : the_post(); // <- here you don't use it
        // it should be:  while ( $query->have_posts() ) : $query->the_post();
            the_content();
        endwhile;
    }
    wp_reset_postdata();
?>

PS. Another suggestion - don't use { and : notation in same context - it's bad for readability ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.