1

I have this code in page.php and it calls the template part for my home. Inside the home.php i used query_posts instead of WP_Query and i wanted to change it into WP_Query.

I tried changing it but it's not working anymore.

This is the previous code using query_posts which is working:

    $args = array(
                'post_type' => 'post',     
                  "orderby"   => "date",
                  "order"     => "DESC",
                  "posts_per_page" => 24,
                'tax_query' => array(
                      'relation' => 'AND',
                               array(
                                 'taxonomy' => 'category',
                                 'terms' => 'uncategorized',
                                 'field' => 'slug'
                               ),
                           array(
                             'taxonomy' => 'creatives-content-types',
                             'terms' => 'newsfeed',
                             'field' => 'slug'
                           )
                        )
                    );
            query_posts($args);
            $count = 0;

            $html_col_o =  '<div>';
            $html_col_t =  '<div>';
            $html_col_th =  '<div>';
            while ( have_posts() ) : the_post();
                $count++;
                $image = get_field('featured_image', $post->ID);
                $size = 'large';            
                $image_url = $image['sizes'][$size];

                $description ="<h2>".get_the_title()."</h2>".get_field('description',$post->ID);
                if($count%3 == 1){
                    $html_col_o = $html_col_o. '<img src="'.$image_url.'" id="img-'.$count.'" data-count="'.$count.'" data-description="'.$description.'"/>';
                } else if($count%3 == 2){
                    $html_col_t = $html_col_t. '<img src="'.$image_url.'" id="img-'.$count.'" data-count="'.$count.'" data-description="'.$description.'"/>';
                } else if($count%3 == 0){
                    $html_col_th = $html_col_th. '<img src="'.$image_url.'" id="img-'.$count.'"  data-count="'.$count.'" data-description="'.$description.'"/>';
                }
            endwhile;

                $html_col_o =  $html_col_o.'</div>';
                $html_col_t =  $html_col_t.'</div>';
                $html_col_th =  $html_col_th.'</div>';
            echo $html_col_o.$html_col_t.$html_col_th;
        ?>

And this is the transformed one using WP_Query but does not work:

    $args = array(
                        'post_type' => 'post',     
                          "orderby"   => "date",
                          "order"     => "DESC",
                          "posts_per_page" => 24,
                        'tax_query' => array(
                              'relation' => 'AND',
                               array(
                                 'taxonomy' => 'category',
                                 'terms' => 'uncategorized',
                                 'field' => 'slug'
                               ),
                           array(
                             'taxonomy' => 'creatives-content-types',
                             'terms' => 'newsfeed',
                             'field' => 'slug'
                           )
                        )
                    );
            $custom_query = new WP_Query($args);
            $count = 0;

            $html_col_o =  '<div>';
            $html_col_t =  '<div>';
            $html_col_th =  '<div>';
            while ( $custom_query->have_posts() ) : $custom_query->the_post();
                $count++;
                $image = get_field('featured_image', $custom_query->$post->ID);
                $size = 'large';            
                $image_url = $image['sizes'][$size];

                $description ="<h2>".get_the_title()."</h2>".get_field('description',$custom_query->$post->ID);
                if($count%3 == 1){
                    $html_col_o = $html_col_o. '<img src="'.$image_url.'" id="img-'.$count.'" data-count="'.$count.'" data-description="'.$description.'"/>';
                } else if($count%3 == 2){
                    $html_col_t = $html_col_t. '<img src="'.$image_url.'" id="img-'.$count.'" data-count="'.$count.'" data-description="'.$description.'"/>';
                } else if($count%3 == 0){
                    $html_col_th = $html_col_th. '<img src="'.$image_url.'" id="img-'.$count.'"  data-count="'.$count.'" data-description="'.$description.'"/>';
                }
            endwhile;

                $html_col_o =  $html_col_o.'</div>';
                $html_col_t =  $html_col_t.'</div>';
                $html_col_th =  $html_col_th.'</div>';
            echo $html_col_o.$html_col_t.$html_col_th;

When i tried adding: echo "count: ".$custom_query->found_posts

it does not return anything.

The sample output: (correct one using query_posts) Correct output using query_posts

And this is what comes out using wp_query

enter image description here

What will i do? is there something wrong with my code? Please help me. Thank You.

  • 1
    Have you realized that you are requesting posts that belongs at the same time to uncategorized and newsfeed categories? The posts must be in both categories to match your WP_Query arguments; is that what you want? – cybmeta Feb 18 '16 at 7:42
  • I have 2 different taxonomies and each post showing in the query_posts is under the uncategorized and newsfeed categories. I designed it that way. How can i show them in WP_Query? – karlo jay bueno Feb 18 '16 at 8:43
1

There should be no reason why you should get results with query_posts and not with WP_Query. query_posts uses WP_Query, so both should work the same.

Your code is really messy and you are using miltiple syntaxes which makes your code hard to debug. This leads hiding obvious bugs and really send you on unnecessary wild goose chases. Also, it is not necessary to set arguments with its default values.

Lets rewrite your code to something more readable and more reliable.

/**
 * Set the query arguments we will use to get posts by
 * Since PHP 5.4 we can use short array syntax, so we can use []
 * instead of array(). You should be on PHP 5.6 already and should not 
 * be using any version prior to 5.6
 */
$args = [ 
    'posts_per_page'   => 24,
    'suppress_filters' => true, // Do not let filters change the query
    'tax_query'        => [
        [ // Removed the relation as AND is default value
            'taxonomy' => 'category',
            'terms'    => 'uncategorized',
            'field'    => 'slug'
        ],
        [
            'taxonomy' => 'creatives-content-types',
            'terms'    => 'newsfeed',
            'field'    => 'slug'
        ]
    ]
];
$custom_query = new WP_Query($args);

if ( $custom_query->have_posts() ) { // Always first make sure you have posts to avoid bugs
    $count = 0;

    $html_col_o  = '<div>';
    $html_col_t  = '<div>';
    $html_col_th = '<div>';

    while ( $custom_query->have_posts() ) {
        $custom_query->the_post();

        $count++;
        $image     = get_field( 'featured_image', get_the_ID() ); // Use get_the_ID() for reliability

        if ( $image ) { //Make sure we have an image to avoid bugs or unexpected output
            $size      = 'large';           
            $image_url = $image['sizes'][$size];

            $description = '<h2>' . get_the_title() . '</h2>' . get_field( 'description', get_the_ID() ); // Again, use get_the_ID()

            if( $count%3 == 1 ) {
                $html_col_o  = $html_col_o  . '<img src="' . $image_url . '" id="img-' . $count . '" data-count="' . $count . '" data-description="' . $description . '"/>';
            } elseif( $count%3 == 2 ) {
                $html_col_t  = $html_col_t  . '<img src="' . $image_url . '" id="img-' . $count . '" data-count="' . $count . '" data-description="' . $description . '"/>';
            } elseif( $count%3 == 0 ) {
                $html_col_th = $html_col_th . '<img src="' . $image_url . '" id="img-' . $count . '" data-count="' . $count . '" data-description="' . $description . '"/>';
            }

        }
    }

    $html_col_o  = $html_col_o  . '</div>';
    $html_col_t  = $html_col_t  . '</div>';
    $html_col_th = $html_col_th . '</div>';

    echo $html_col_o . $html_col_t . $html_col_th;

    wp_reset_postdata(); // VERY VERY IMPORTANT, restes the $post global back to the main query
}

You can now do echo $custom_query->request to inspect the generated SQL query, alternatively, you can do var_dump( $custom_query ) to inspect the complete query object. You should also turn debug on and look for obvious bugs.

But as I said, there should be no reason why query_posts works and WP_Query not

  • Wow. Thanks @pieter . It works. I'm still a newbie in wordpress, but the codes you did works. if you don't mind, can i ask you for an explanation for the codes? – karlo jay bueno Feb 19 '16 at 0:18
  • My pleasure, glad it worked. I have update the code to include comments. I hope that helps. Enjoy ;-) – Pieter Goosen Feb 19 '16 at 4:16
  • Thank you so much, @pieter. I will follow your coding convention then. That's a really great advice ;) – karlo jay bueno Feb 19 '16 at 4:22

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.