Skip to content

Instantly share code, notes, and snippets.

@bradleysa
Created April 22, 2022 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradleysa/ad4363c0087a2d396ee3893930a50089 to your computer and use it in GitHub Desktop.
Save bradleysa/ad4363c0087a2d396ee3893930a50089 to your computer and use it in GitHub Desktop.
Display Random Posts: Recipe
function wpdean_rand_posts() {
$args = array(
'post_type' => 'recipe',
'orderby'=> 'rand',
'posts_per_page' => 3,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$string .= '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
}
$string .= '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
}
else {
$string .= 'no posts found';
}
return $string;
}
add_shortcode('wpdean-random-posts','wpdean_rand_posts');
add_filter('widget_text', 'do_shortcode');
/** https://blog.hubspot.com/website/show-random-posts-wordpress **/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment