I have a shortcode that works to display posts from specific categories, or a single post based on the post slug. I'm having trouble figuring out how to get it to display multiple posts based on their slugs though. I know I need to use explode, but I can't seem to get it right.
Here's the current working code:
add_shortcode( 'latest_post', 'latest_post_query_shortcode' );
function latest_post_query_shortcode( $atts ) {
ob_start();
$atts = shortcode_atts( array(
'posts_per_page' => '',
'category' => '',
'offset' => '',
'post' => '',
), $atts );
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page'=> $atts['posts_per_page'],
'offset' => $atts['offset'],
);
// Add category if not empty
if ( ! empty ( $atts['category'] ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $atts['category'],
),
);
}
// Add post if not empty
if ( ! empty ( $atts['post'] ) ) {
$args['name'] = $atts['post'];
}
$string = '';
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) { ?>
<section class="recent-posts clear">
<?php while ( $query->have_posts() ) : $query->the_post() ; ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( 'left' ); ?>>
<? echo '<a href="' . get_permalink( $_post->ID ) . '" title="' . esc_attr( $_post->post_title ) . '">';
echo get_the_post_thumbnail( $_post->ID, 'large' );
echo '</a>';
echo '<h2><a href="' . get_permalink( $_post->ID ) . '" title="' . esc_attr( $_post->post_title ) . '">';
echo get_the_title( $_post->ID);
echo '</a></h2>';
?>
</article>
<?php endwhile;
wp_reset_postdata();?>
</section>
<?php
$clean = ob_get_clean();
return $clean;
}
}
I tried adding:
'name' => explode( ', ', $post),
inside
$args = array(
but that didn't return anything when I tried specifying two slugs, for example: [latest_post post="almond-cake, coconut-pie"] (If I use either one of those, it works, but not both.)
Additionally once I added the explode, it game me this warning everywhere else the shortcode was used:
Warning: trim() expects parameter 1 to be string, array given...