0

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...

1

2 Answers 2

2

So from the WP_Query page, I found this, which is like $args['name'] but for when you want to search for many slugs:

post_name__in (array) – use post slugs. Specify posts to retrieve. (Will be available in version 4.4)

I think this is maybe what you need?

In that case you'd need to explode $atts['post'] on "," as you did, then pass that resulting array to post_name__in attribute in $attrs. You're getting that error resulting from trim because you're passing an array to the 'name' attribute in WP Query which is expecting a single slug name in a string.

I'd recommend you explode on "," first, without spaces, then strip off the white space from the resulting strings as that allows for much more freedom in how you (or other users) put stuff in the post attribute in the shortcode.

Let me know if that is or isn't on the right track or if you want more detailed code example

3
  • That looks like it's what I need! When I try to explode now (under the $args array) all instances of the shortcode go blank (because they're expecting a slug?) so I added it like this: if ( ! empty ( $atts['post'] ) ) { $args['post_name__in'] = explode( ',', $post); } But obviously that's not right because now it's not showing anything.
    – Christina
    Jun 22, 2020 at 23:07
  • that should work. I think you missed $atts off the end there: if ( ! empty ( $atts['post'] ) ) { $args['post_name__in'] = explode( ',', $atts['post']); }
    – mozboz
    Jun 22, 2020 at 23:11
  • oops, maybe you took that from my answer which was wrong.. fixed it :)
    – mozboz
    Jun 22, 2020 at 23:12
0

This works for me:

add_shortcode( 'latest_post', 'latest_post_query_shortcode' );
function latest_post_query_shortcode(  $atts ) {
        ob_start();
        $atts = shortcode_atts( array(
                        'posts_per_page' => '',
                        'category' => array(), // defined as array here
                        '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'] ) ) {
            $terms = str_replace(' ', '', $atts['category']); // strip whitespace so admins don't have to remember whether or not to put a space after each comma
            $terms = explode(',', $atts['category']); // then get the array
            $args['tax_query']  = array( 
                    array(
                            'taxonomy'  => 'category',
                            'field'     => 'slug',
                            'terms' => $terms,
                    ), 
            );    
        }
        
        // 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( $query->ID ) . '" title="' . esc_attr( $query->post_title ) . '">';
                                        echo get_the_post_thumbnail( $query->ID, 'large' );
                                        echo '</a>';
                                        echo '<h2><a href="' . get_permalink( $query->ID ) . '" title="' . esc_attr( $query->post_title ) . '">';
                                        echo get_the_title( $query->ID);
                                        echo '</a></h2>';

                                ?>
                        </article>
                <?php endwhile; 
                wp_reset_postdata();?>  
                </section>          
                <?php 
                $clean = ob_get_clean();
                return $clean;      
        }
}
1
  • Thanks Michelle! I can see how that would work for categories, but I'm trying to show multiple post slugs like: [latest_post post="almond-cake, coconut-pie"] It works when I do just one, but not both.
    – Christina
    Jun 22, 2020 at 21:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.