Ask your WordPress questions! Pay money and get answers fast! (more info)

Best way to check for [gallery] shortcode in plugin overriding it WordPress

  • SOLVED

Here's a sample of code from the plugin I'm using that turns [gallery] into a slideshow:

// Check for [gallery] shortcode
function have_gallery( $posts ) {
if ( empty( $posts ) || $this->has_gallery )
return $posts;

foreach ( $posts as $post ) {
$pos = strstr( $post->post_content, '[gallery' );
if ( false !== $pos && $pos >= 0 ) {
$this->has_gallery = true;
break;
}
}

if ( $this->has_gallery )
$this->enqueue_assets();

return $posts;

}


The plugin/code works fine if the [gallery] shortcode is within the page/post content (WYSIWYG / HTML editor) area, but it doesn't work if do_shortcode('[gallery]'); is used in a page template... AND [gallery] is not in the content area.

Said another way, I have to type [gallery] into the WYSIWYG area in order for do_shortcode('[gallery]'); to work... EVEN THOUGH the content isn't displayed on the page/post/CPT template.

Is there a way to edit/rewrite the code above to be able to play nice with do_shortcode WITHOUT having to do that little trick of entering [gallery] into the WYSIWYG area?

FYI: Related question here: [[LINK href="http://wordpress.stackexchange.com/questions/70649/wp-insert-post-data-for-cpt"]]http://wordpress.stackexchange.com/questions/70649/wp-insert-post-data-for-cpt[[/LINK]]

Thank you.

Answers (1)

2012-10-27

Arnav Joy answers:

if you not use [gallery] shortcode in WYSIWYG then how we will know page has a gallery..


Clifford P comments:

I upload images to create the gallery but then want to use it in a page template. Like I said, all works perfectly if I put [gallery] in the content area even though I don't display it at all on the page.


Arnav Joy comments:

try this

<?php




function have_gallery( $posts ) {

if ( empty( $posts ) || $this->has_gallery )

return $posts;



foreach ( $posts as $post ) {

$pos = strstr( $post->post_content, '[gallery' );

$args = array(
'post_type' => 'attachment',
'numberposts' => null,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts($args);



if( !empty($attachments )) {

$this->has_gallery = true;

break;

}

}



if ( $this->has_gallery )

$this->enqueue_assets();



return $posts;



}
?>


Clifford P comments:

Worked just as desired. Thank you SO much! :-)