Support » Fixing WordPress » Counting the number of images in a post

  • Hi

    What I am trying to do can be best described by looking at this previous thread.

    Whilst I have worked through that method and included the PHP, I am getting random numbers coming out that seem to have no reference to the post they are referring to. There seems to be no logic to what number are spat out!

    This is the code I have in place below – is there something I should be calling to get the post ID?

    <?php
    						$id=the_ID();
    						$total_attachments = $wpdb->get_var("SELECT COUNT(ID) FROM {$wpdb->prefix}posts WHERE post_type = 'attachment' && ID=$id");
    						echo $total_attachments;
    					?>

    Thanks,

    Ian

Viewing 8 replies - 1 through 8 (of 8 total)
  • Thread Starter applegateian

    (@applegateian)

    OK thanks…I tried dropping that in instead. Is there anything else I should change as it’s now returning the number 0 for all.

    Just to confirm, this is on the home page so needs to work out that the snipped shown is post ID X

    Cheers

    this is on the home page

    where exactly is the code?
    it has to be in the loop to work.

    Thread Starter applegateian

    (@applegateian)

    I believe it is in the loop – here is the code from the loop down…..The loop ends further down the page, but ‘imageCount’ is where I am trying to run this. Thanks for your help.

    <?php query_posts('showposts='.$breaking_num.'&cat='.$breaking_cat.'');
          while (have_posts()) : the_post();  
    
        ?>  
    
        <div class="homeFeatured">  
    
            <div class="featuredImageFrame">
    			<img src="<?php echo get_post_meta($post->ID, 'featuredimage',true) ?>" alt="Post Image" class="postimg" />  
    
    		</div>
    				<div class="imageCount">
    					<?php
    						$id=get_the_ID();
    						$total_attachments = $wpdb->get_var("SELECT COUNT(ID) FROM {$wpdb->prefix}posts WHERE post_type = 'attachment' && ID=$id");
    						echo $total_attachments;
    					?>
    Thread Starter applegateian

    (@applegateian)

    Hey all, does anyone have any more suggestions on this? Still pulling back a ‘0’ count on this.

    Thanks,

    Ian

    Try this:

    $pid=get_the_ID();
    $images =& get_children( "post_type=attachment&post_mime_type=image&post_parent=$pid" );
    $count = count($images);

    I think the code you were using is querying an old version of the wp database. Also, when using $wpdb->get_var, you need to declare global $wpdb

    Thread Starter applegateian

    (@applegateian)

    Hi again

    Thanks for the suggestion. Unfortunately this is returning a blank. Previously it was giving random numbers, now it just returns nothing.

    Any other tweaks to this I could make?

    Thanks again.

    even i am looking for the same ….

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Counting the number of images in a post’ is closed to new replies.