First three images in post excerpt

You can do this pretty easily using the do_shortcode function.

Check if an instance of exists in your post content.

Here’s a simple function to drop in functions.php that checks the current post’s content for the gallery shortcode:

function gallery_shortcode_exists(){

    global $post;

    # Check the content for an instance of  with or without arguments
    $pattern = get_shortcode_regex();
    if(
        preg_match_all( "https://wordpress.stackexchange.com/". $pattern .'/s', $post->post_content, $matches )
        && array_key_exists( 2, $matches )
        && in_array( 'gallery', $matches[2] )
    )
        return true;

    # Sourced from http://codex.wordpress.org/Function_Reference/get_shortcode_regex
}

Use do_shortcode() to render your gallery.

You can use the following within the loop in your template files:

# Determine if the post_content column contains the string 
if( gallery_shortcode_exists() ){

    # Get the first three attachments using the posts_per_page parameter
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'posts_per_page' => 3,
        'post_parent' => get_the_ID()
    );
    $attachments = get_children( $args );

    # If any attachments are returned, proceed
    if( $attachments ){

        # Spin cycle to collate attachment IDs
        foreach( $attachments as $attachment )
            $includes[] = $attachment->ID;

        # Format our IDs in a comma-delimited string
        $includes = implode(',', $includes);

        # Inject your include argument
        $shortcode = str_replace('[gallery', "[gallery include="$includes" ", get_the_content());

        # Render the Gallery using the standard editorial input syntax
        echo do_shortcode($shortcode);

        # Add a View More link
        echo '<a href="' . get_permalink() . '">' . __('View more', 'domain') . '</a>';
    }
    else
        _e('Foo Bar - No attachments found and no excerpt to display', 'domain');
}
else
    # Whatever fallback you desire
    the_excerpt();

Leave a Comment