php - Popular Post with wp_query and date_query wordpress -
i trying create popular post section on website show top 5 popular posts of past week.
function popular post
function shapespace_popular_posts($post_id) { $count_key = 'popular_posts'; $count = get_post_meta($post_id, $count_key, true); if ($count < 1) { delete_post_meta($post_id, $count_key); add_post_meta($post_id, $count_key, '0'); } else { $count++; update_post_meta($post_id, $count_key, $count); } } function shapespace_track_posts($post_id) { if (!is_single()) return; if (empty($post_id)) { global $post; $post_id = $post->id; } shapespace_popular_posts($post_id); } add_action('wp_head', 'shapespace_track_posts');
loop popular post
<?php $popular = new wp_query(array( 'posts_per_page'=>5, 'date_query' => array( //set date ranges strings! 'after' => '1 week ago', 'before' => 'today', //allow exact matches returned 'inclusive' => true, ), 'meta_key'=>'popular_posts', 'orderby'=>'meta_value_num', 'order'=>'desc')); while ($popular->have_posts()) : $popular->the_post(); ?> <h5 class="section_category"> <?php the_category(', ') ?> </h5> <div class="trending_title"> <?php the_title( sprintf( '<h4><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h4>' ); ?> </div> <h5 class="section_author"> <?php coauthors_posts_links(); ?> </h5> <div class="border-bottom"></div> <?php endwhile; wp_reset_postdata(); ?>
if can in anyway greatful.
thank you,
use "query_posts" instead of "wp_query"
<?php $args = array( 'post_type' => 'post', 'showposts' => 5, 'date_query' => array( //set date ranges strings! 'after' => '1 week ago', 'before' => 'today', //allow exact matches returned 'inclusive' => true, ), 'meta_key' => 'popular_posts', 'orderby' => 'meta_value_num', 'order' => 'desc' ); query_posts($args); //query_posts('post_type=post&showposts=5&meta_key=popular_posts&orderby=meta_value_num&order=desc'); if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <h5 class="section_category"> <?php the_category(', ') ?> </h5> <div class="trending_title"> <?php the_title( sprintf( '<h4><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h4>' ); ?> </div> <h5 class="section_author"> <?php coauthors_posts_links(); ?> </h5> <div class="border-bottom"></div> <?php endwhile; ?> <?php endif; wp_reset_query(); ?>
Comments
Post a Comment