Last active
April 18, 2024 13:40
-
-
Save mwender/889feb7698ce0e1394a8aa98f2051877 to your computer and use it in GitHub Desktop.
[WordPress Elementor Trending Posts Shortcode] In conjunction with the Post Views Counter plugin, the following provides a "trending_posts" shortcode for use in displaying an Elementor Loop Template #elementor #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 | |
/** | |
* A shortcode for querying a set of trending posts from the Post Views | |
* Counter plugin. Then it outputs those posts inside an Elementor Loop | |
* Template that you specify. | |
*/ | |
function trending_posts_shortcode($atts) { | |
$args = shortcode_atts([ | |
'template' => null, | |
'limit' => 5, | |
], $atts ); | |
// Query parameters | |
$query_args = array( | |
'order' => 'DESC', | |
'orderby' => 'post_views', | |
'suppress_filters' => false, | |
'fields' => '', | |
'post_type' => 'post', | |
'post_status' => 'publish', | |
'posts_per_page' => intval($args['limit']), // Convert limit to integer | |
); | |
// The WP_Query | |
$query = new WP_Query($query_args); | |
// Output variable | |
$output = ''; | |
// Check if the template ID is set and valid | |
if ( ! empty( $args['template'] ) ) { | |
if ($query->have_posts()) { | |
while ($query->have_posts()) { | |
$query->the_post(); | |
// Temporarily switch to the post specified by the ID | |
global $post; | |
$post = get_post(get_the_ID()); | |
// Output the Elementor template for each post | |
ob_start(); | |
echo '<div style="margin-bottom: 1rem; border: 2px solid #98002E;">' . do_shortcode('[elementor-template id="' . $args['template'] . '"]') . '</div>'; | |
$output .= ob_get_clean(); | |
} | |
wp_reset_postdata(); // Reset post data after the loop | |
} | |
} else { | |
$output = '<p>Please specify a Template ID (' . $args['template'] . ').</p>'; | |
} | |
return $output; | |
} | |
// Register the shortcode with WordPress | |
add_shortcode('trending_posts', 'trending_posts_shortcode'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment