[resolved] Check if post has gallery (3 posts)

  1. Waqas
    Posted 4 years ago #

    I want to use if else condition of post has gallery..

    the following example checks if post has thumb. how to make it check for gallery?

            if(has_post_thumbnail()) { ?>
    1st choice
            <?php } else { ?>
    2nd choice
    <?php } ?>
  2. Twintails
    Posted 4 years ago #

    Heres a Snippet I made, not sure if it's the right thing to do, but it worked for me on a "from Scratch" theme I built:

    //place within the PHP on your functions.php page
    function mypost_has_gallery($postid)
    		//SELECT * FROM <code>wp_posts</code> WHERE
    		//AND (<code>wp_posts</code>.<code>post_parent</code>="postID")
    		//AND (LOCATE("image",<code>wp_posts</code>.<code>post_mime_type</code>)>0))
    		global $wpdb;
    		$table = $wpdb->prefix . "posts";
    		$sql = "SELECT * FROM <code>&quot; . $table . &quot;</code> WHERE ((<code>&quot; . $table . &quot;</code>.<code>post_type</code>=\"attachment\") AND (<code>&quot; . $table . &quot;</code>.<code>post_parent</code>=\"" . $postid ."\") AND (LOCATE(\"image\",<code>&quot; . $table . &quot;</code>.<code>post_mime_type</code>)>0))";
    		if ( $wpdb->get_var($sql) != 0 ){
    			return true;}
    			return false;
    //Insert on the page
    <?php $postid = get_the_ID();
    if ( mypost_has_gallery($postid) ) {?>
            	//do something
           <?php } ?>

    Here is what's on my page (There's a default image for pages in the last else statement)

    <div id="postimage" >
    		<?php if( has_post_thumbnail()) {
    				//check for featured image on page or post
                    $image_src = wp_get_attachment_image_src( get_post_thumbnail_id(), "full" );
                    echo "<img border=\"0\" src=\"". $image_src[0] ."\" >"; //IE image Border 0 for images inside links
            		} // if the page doesn't have a featured image, but instead has a gallery of attached images do this...
    				else if ( mypost_has_gallery($postid) ) {
                		// Place the Gallery automagically on the page
                		echo do_shortcode('[gallery link="post"]');
    				} // if there is no image fallback to this default
    				else { ?>
                    	<img src="<?php bloginfo('template_directory'); ?>/featimg.png" alt="<?php the_title(); ?>" />
    		<?php }	?>

    If that was clear as mud, I'll try to de-obfuscate it, let me know.

  3. Waqas
    Posted 4 years ago #

    I'm using this one since an year

    if (strpos($post->post_content,'[gallery') !== false){
    echo do_shortcode('[gallery]');
    } else {

Topic Closed

This topic has been closed to new replies.

About this Topic