Skip to content

Instantly share code, notes, and snippets.

@ajaydsouza
Last active July 25, 2023 19:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajaydsouza/c8defd4b46e53240e376 to your computer and use it in GitHub Desktop.
Save ajaydsouza/c8defd4b46e53240e376 to your computer and use it in GitHub Desktop.
Top 10 API examples
<?php
/*
* This example fetches the popular posts tracked by Top 10.
*
*/
if ( function_exists( 'get_tptn_posts' ) ) {
$settings = array(
'daily' => TRUE,
'daily_range' => 30,
'limit' => 20,
'strict_limit' => FALSE,
);
$topposts = get_tptn_posts( $settings ); // Array of posts
$topposts = wp_list_pluck( (array) $topposts, 'postnumber' );
$args = array(
'post__in' => $topposts,
'orderby' => 'post__in',
'posts_per_page' => 7,
'ignore_sticky_posts' => 1
);
$my_query = new WP_Query( $args );
if ( $my_query->have_posts() ) {
while ( $my_query->have_posts() ) {
$my_query->the_post();
echo '<a href="' . get_permalink( get_the_ID() ) . '">';
the_title();
echo '</a>';
wp_reset_postdata();
}
} else {
}
wp_reset_query();
}
<?php
// Show Top 10 popular posts in Posts Widget.
// Change my_custom_filter with the filter you are using.
add_action( 'elementor_pro/posts/query/my_custom_filter', function( $query ) {
$settings = array(
'daily' => TRUE,
'daily_range' => 30,
'limit' => 20,
'strict_limit' => FALSE,
);
$topposts = get_tptn_posts( $settings );
$posts_in[] = wp_list_pluck( (array) $topposts, 'postnumber' );
// Here we set the query to fetch posts with
// ordered by comments count
$query->set( 'post__in', $posts_in );
$query->set( 'orderby', $posts_in );
} );
<?php
/**
* Add comments count to the list items.
*
* @param string $output Formatted list item with link and and thumbnail
* @param object $result Object of the current post result
* @param array $args Array of arguments
*
* @return string Output variable with comments number added
*/
function tptn_comments_count( $output, $result, $args ) {
$output .= " " . $result->comment_count . " comments";
return $output;
}
add_filter( 'tptn_list', 'tptn_comments_count' , 10, 3 );
<?php
/**
* Add categories to the list items.
*
* @param string $output Formatted list item with link and and thumbnail
* @param object $result Object of the current post result
* @param array $args Array of arguments
*
* @return string Output variable with categories added
*/
function tptn_list_cats( $output, $result, $args ) {
$categories = get_the_category_list( ", ", "", $result->ID );
$output .= " " . $categories;
return $output;
}
add_filter( 'tptn_list', 'tptn_list_cats' , 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment