Random Posts Shortcode
Shortcode [scseed_random_posts] that outputs a randomised list of published posts.
PHPby SnipCraft
php
<?php
add_shortcode( 'scseed_random_posts', 'scseed_random_posts_shortcode' );
if ( ! function_exists( 'scseed_random_posts_shortcode' ) ) {
function scseed_random_posts_shortcode( $atts ) {
$atts = shortcode_atts( [
'count' => 5,
'post_type' => 'post',
'show_thumb' => false,
], $atts, 'scseed_random_posts' );
$query = new WP_Query( [
'post_type' => sanitize_key( $atts['post_type'] ),
'posts_per_page' => absint( $atts['count'] ),
'orderby' => 'rand',
'post_status' => 'publish',
'no_found_rows' => true,
] );
if ( ! $query->have_posts() ) {
return '';
}
$out = '<ul class="scseed-random-posts">';
while ( $query->have_posts() ) {
$query->the_post();
$out .= '<li class="scseed-random-posts__item">';
if ( filter_var( $atts['show_thumb'], FILTER_VALIDATE_BOOLEAN ) && has_post_thumbnail() ) {
$out .= '<a href="' . esc_url( get_permalink() ) . '">'
. get_the_post_thumbnail( null, 'thumbnail' ) . '</a> ';
}
$out .= '<a href="' . esc_url( get_permalink() ) . '">'
. esc_html( get_the_title() ) . '</a>';
$out .= '</li>';
}
$out .= '</ul>';
wp_reset_postdata();
return $out;
}
}#content#display#posts#shortcode