Skip to content

Instantly share code, notes, and snippets.

@DeoThemes
Created August 16, 2017 02:41
Show Gist options
  • Save DeoThemes/4941ee94f153098a6c130e33a9793589 to your computer and use it in GitHub Desktop.
Save DeoThemes/4941ee94f153098a6c130e33a9793589 to your computer and use it in GitHub Desktop.
Get first gallery shortcode WordPress
<?php
function deo_get_attachment(){
global $post;
$pattern = get_shortcode_regex();
$output = '';
if( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
&& array_key_exists( 2, $matches )
&& in_array( 'gallery', $matches[2] ) ):
$keys = array_keys( $matches[2], 'gallery' );
foreach( $keys as $key ):
$atts = shortcode_parse_atts( $matches[3][0] );
if( array_key_exists( 'ids', $atts ) ):
$attachments = get_posts( array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post__in' => explode( ',', $atts['ids'] ),
'orderby' => 'post__in'
) );
endif;
endforeach;
return $attachments;
elseif( has_post_thumbnail() ):
$output = wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) );
endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment