May. 24, 2011

No!

Click to download blog-post.doc

No comments \ Leave a comment
May. 02, 2011

Two methods to get number of images in a WordPress post

Supposing that you had a post ID number, you can retrieve number of images inside the post in two ways:

  1. by retrieving post attachments, or,
  2. by parsing the HTML.

Neither method is fullproof.  The first one fails to identify whether an image is inserted (though attached) and the second one fails to identify whether an image is commented out. All the same, here they are as functions:

Attachment method:

function post_photo_count_attachments( $post_id ) {
 
	$attachments = get_children(
		array( 'post_parent' => $post_id ) 
	);
 
	return( count( $attachments ) );
}

Xpath method:

function post_photo_count_xpath( $post_id ) {
	global $wpdb;
 
	$post_id_safe = intval( $post_id );
 
	$html = $wpdb->get_row(
		"select * from {$wpdb->posts} where ID={$post_id_safe} limit 1"
	);
 
	$doc = new DOMDocument();
	@$doc->loadHTML( $html->post_content );
	$path = new DOMXpath( $doc );
	$images = $path->query( "//img" );
 
	return( $images->length );
}

Of course, mix and match these as you see fit.

No comments \ Leave a comment
Posts on this blog solely represent my personal opinions and technical experience.

© 2009-2017 Edin (Dino) Beslagic