Skip to content

Instantly share code, notes, and snippets.

@moskalukigor
Last active February 21, 2018 13:07
Show Gist options
  • Save moskalukigor/0585065f7409e9d910ea06e89a5cfd5d to your computer and use it in GitHub Desktop.
Save moskalukigor/0585065f7409e9d910ea06e89a5cfd5d to your computer and use it in GitHub Desktop.
popular product wordpress
<?php
function get_most_popular_products($atts = array())
{
extract($atts);
$posts_per_page = !isset( $posts_per_page ) ? 10 : $posts_per_page;
$order = !isset( $order ) ? "DESC" : $order;
$post_status = !isset( $post_status ) ? "publish" : $post_status;
$post_type = !isset( $post_type ) ? "product" : $post_type;
$args = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'post_status' => $post_status,
'order' => $order,
'orderby' => 'meta_value_num',
'meta_key' => 'post_views_count',
);
$custQuery = new WP_Query($args);
?>
<ul class="products">
<?php
if ($custQuery->have_posts()) : while ($custQuery->have_posts()) : $custQuery->the_post();
wc_get_template_part('content', 'product');
endwhile; endif;
?>
</ul>
<?php
wp_reset_postdata();
}
/*
* Set post views count using post meta
*/
function setPostViews($postID) {
$countKey = 'post_views_count';
$count = get_post_meta($postID, $countKey, true);
if($count == '' || $count == null){
$count = 0;
update_post_meta($postID, $countKey, $count);
}else{
$count++;
update_post_meta($postID, $countKey, $count);
}
}
<?php
setPostViews(get_the_ID());
//BEFORE get_header('shop');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment