0

I'm trying to add a function to my site that will count the number of images attached to a post, and if only one, to add a class to either that <img> or to the containing <a>.

I think I'm fairly close, but don't have the PHP syntax skills to finish it up. The code I've hacked together, sourced from various threads on the topic, is:

/**
 *
 * Single-image posts will receive a separate class name
 *
 */

add_filter( 'the_content', 'single_image_content_filter', 20 );

// Count images in post
function single_image_content_filter( $content ) {

$attachments = get_children(array('post_parent'=>$post->ID));
$imgcount = count($attachments);

    // If only one attachment, add a new CSS class
    if ( $imgcount === 1 ) {

        global $post;
        $classes = 'single-img'; // separated by spaces, e.g. 'img image-link'

        // check if there are already classes assigned to the anchor, and/or add one via $classes
        if ( preg_match('/<a.*? class=".*?">/', $content) ) {
        $content = preg_replace('/(<a.*? class=".*?)(".*?>)/', '$1 ' . $classes . '$2', $content);
      } else {
        $content = preg_replace('/(<a.*?)>/', '$1 class="' . $classes . '" >', $content);
      }

return $content;

    }
}
  • Can you better not use JavaScript for this? Like: $('.post img:first'); for example – pascalvgemert May 17 '14 at 19:28
  • I don't want it to just target the first out of a possible many images. I want it to only add a class if only one image is found. – dmoz May 17 '14 at 19:36
  • You can still do that with JS, something like: if($('.post img').length == 1) { $('.post img').addClass('some-class'); } – pascalvgemert May 17 '14 at 19:38
  • Any way to get me the full code (answer), and where would be the best place to put it? – dmoz May 17 '14 at 19:42
  • Not today, tomorrow I have some time. Maybe another user can work it out? – pascalvgemert May 17 '14 at 19:46
1

Using @pascalvgemert's suggestion as a starting point, I'm using the following script:

jQuery(document).ready(function() {
    var imgCount = jQuery(".single-post #content-left p a").children("img").length;
    if (imgCount == 1) {
    jQuery("img").addClass("lone-image");
    }
});

Works like a charm.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.