0

I have this code before to show posts.

$query_args = array(
                'post_type' => 'post',
                'posts_per_page' => 4,
                'meta_key' => 'Views',
                'orderby' => 'meta_value_num',
                'order' => 'DESC',
                'ignore_sticky_posts' => true
);
$the_query = new WP_Query( $query_args );
if( $the_query->have_posts() )
{
    while( $the_query->have_posts() )
    {
        $the_query->the_post();                 
        echo    '<a class="popularPostLinks" href="' . get_the_permalink() . '" rel="external" target="_blank">' . get_the_post_thumbnail() . '
                        <br>
                        <div>
                            <p>' . get_the_title() . '</p>
                        </div>
                </a>';
    }
}
else
{
    // No posts found.
}
// Restore original post data.
wp_reset_postdata();

but now i am using my custom query:

$getAllTimeRows = $wpdb->get_results( $wpdb->prepare( "SELECT post_id, SUM( post_value ) AS 'Views' FROM {$wpdb->prefix}PopularPosts GROUP BY post_id ORDER BY Views DESC LIMIT 4" ) );

How can i used this above array result to show posts same like how WP Query is showing the posts? The $getAllTimeRows contains rows (max 4) to show (max 4) posts. See below the array.

print_r ( $getAllTimeRows  )

Array
(
    [0] => stdClass Object
        (
            [post_id] => 213
            [Views] => 16
        )

    [1] => stdClass Object
        (
            [post_id] => 215
            [Views] => 11
        )

    [2] => stdClass Object
        (
            [post_id] => 217
            [Views] => 9
        )

    [3] => stdClass Object
        (
            [post_id] => 227
            [Views] => 7
        )

)

1 Answer 1

0

You can get same result by outputting values from PHP array. Since it is multicolumn array, you will need to run foreach loop and get values of each child item.

Mostly it's standard PHP stuff, nothing special. Although earlier you did not need to supply post ID in each WordPress function since you were using it inside a loop, but now you will have to do that.

So here is the output.

foreach( $getAllTimeRows as $getAllTimeRow ) {

    $post_id_num = $getAllTimeRow->post_id;

    echo '<a class="popularPostLinks" href="' . get_permalink( $post_id_num ) . '" rel="external" target="_blank">' . get_the_post_thumbnail( $post_id_num ) . '<br>
        <div>
            <p>' . get_the_title( $post_id_num ) . '</p>
        </div>
    </a>';

}
2
  • thanks alot. i am new to wordpress and this is really helpful to me. again thanks
    – Hassan Ali
    Dec 16, 2014 at 3:44
  • Sure, no problem. :) I am glad I could help you with this.
    – Robert hue
    Dec 16, 2014 at 3:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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