• Resolved muhammadwaqas

    (@muhammadwaqas)


    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?

    <?php
            if(has_post_thumbnail()) { ?>
    1st choice
            <?php } else { ?>
    2nd choice
    <?php } ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • 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
    		//((<code>wp_posts</code>.<code>post_type</code>="attachment")
    		//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;}
    		else{
    			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 }	?>
           </div>

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

    Thread Starter muhammadwaqas

    (@muhammadwaqas)

    I’m using this one since an year

    <?php
    if (strpos($post->post_content,'[gallery') !== false){
    echo do_shortcode('[gallery]');
    } else {
    the_post_thumbnail();
    }
    ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Check if post has gallery’ is closed to new replies.