Last active
February 21, 2018 13:07
-
-
Save moskalukigor/0585065f7409e9d910ea06e89a5cfd5d to your computer and use it in GitHub Desktop.
popular product wordpress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// GET POPULAR POSTS | |
// Can be used without attributes get_most_popular_products() - OK | |
get_most_popular_products(array('posts_per_page' => 5, 'order' => 'DESC', 'post_status' => 'publish', 'post_type' => 'product' )); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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