0

I have code that works fine on our live system, and I'm porting it to a new theme. In the new theme, the WP_Query always seems to return the last custom post.

My function is:

    function get_wpinfo( $entry) {
        global $post;
        $resp_array = array();
        $args = array( 
            'posts_per_page'=> 1,
            'post_type'     => 'table_element',
            'post_status'   => 'publish',
            'post_name'         => $entry       );
        print "Args = "; var_dump( $args );
        $query = new WP_Query( $args );
        if ( $query->have_posts() ) {
            $query->the_post();
            print_r( $post );
        }
        wp_reset_postdata();
        return  $resp_array;
    }

The output from the first print is:

    Args = array(4) {
        ["posts_per_page"]=>  int(1)
        ["post_type"]=>  string(13) "table_element"
        ["post_status"]=>  string(7) "publish"
        ["post_name"]=>  string(2) "24"
    }

And the output from the print_r is:

    WP_Post Object
    (
        [ID] => 4239
        [post_author] => 1
        [post_date] => 2015-08-25 19:00:44
        [post_date_gmt] => 2015-08-25 19:00:44
        [post_content] => Source: <a href="https://www.linkedin.com/pulse/5-predictions-predictive-analytics-2015-mark-rabkin" target="“_blank">5 Analytics Predictions 2015</a>
        [post_title] => 2
        [post_excerpt] => 
        [post_status] => publish
        [comment_status] => closed
        [ping_status] => closed
        [post_password] => 
        [post_name] => 2
        [to_ping] => 
        [pinged] => 
        [post_modified] => 2015-08-25 19:00:44
        [post_modified_gmt] => 2015-08-25 19:00:44
        [post_content_filtered] => 
        [post_parent] => 0
        [guid] => http://www.meshagency-salient.com.php53-17.dfw1-2.websitetestlink.com/?post_type=table_element&p=4239
        [menu_order] => 0
        [post_type] => table_element
        [post_mime_type] => 
        [comment_count] => 0
        [filter] => raw
    )

At first, the code was always returning the Custom Post with slug "99". Then I realized, it was returning the last post created. I deleted and re-created posts "1 and "2" and now it always returns "2".

Any ideas would be greatly appreciated!

0

There is no post_name argument for WP_Query, if you're querying by slug, it's just name. Without that argument, your query just gets the latest post back.

  • Wow! Thank you. I can't believe I've been looking at this all day and missed that. – user3147421 Aug 25 '15 at 21:33

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.