Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ Below is the list of useful WordPress Snippets that you can use when developing
+ [Get random post suggestion by tags](https://github.com/dalenguyen/wordpress-snippets/blob/master/src/get_random_post_suggestion_by_tags.php)
+ [Remove inline styling from tag cloud](https://github.com/dalenguyen/wordpress-snippets/blob/master/src/remove_inline_styling_from_tag_cloud.php)
+ [Show related posts on single](https://github.com/wajidalitabassum143/wordpress-snippets/blob/master/src/show_related_posts_on_single.php)
+ [Shortcode: show popular blog posts based on cat](https://github.com/wajidalitabassum143/wordpress-snippets/blob/master/src/show_popular_blog_posts_based_on_cat_shortcode.php)
87 changes: 87 additions & 0 deletions src/show_popular_blog_posts_based_on_cat_shortcode.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

// Popular posts - counting hits
function wp_popular_posts( $post_id ) {

$count_key = 'popular_posts';

$count = get_post_meta( $post_id, $count_key, true );

if ( $count == '' ) {

$count = 0;

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 wp_track_posts( $post_id ) {

if ( ! is_single() ) return;

if ( empty( $post_id ) ) {

global $post;

$post_id = $post->ID;

}

wp_popular_posts( $post_id );

}
add_action( 'wp_head', 'wp_track_posts' );


// Shortcode: display popular posts based on cat
add_shortcode( 'popular-posts', 'wp_display_popular_posts' );
function wp_display_popular_posts( $atts, $content = null ) {

ob_start();

extract( shortcode_atts( array(
'num' => 5,
'cat' => '',
), $atts ) );

$temps = explode( ',', $cat );

$array = array();

foreach ( $temps as $temp ) $array[] = trim( $temp );

$cats = ! empty( $cat ) ? $array : '';

echo'<ul class="rp-posts">';

$popular = new WP_Query( array(
'posts_per_page' => $num,
'meta_key' => 'popular_posts',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'category__in' => $cats
) );

while ( $popular->have_posts() ) : $popular->the_post();

echo'<li><a href="'. get_the_permalink() .'">'. get_the_title() .'</a></li>';

endwhile;

wp_reset_postdata();

echo'</ul>';

return ob_get_clean();

}