0

I would like to use a simple function in order to add a specific attribute (lets call it “example”) to the first image of every blog post, so that I don't have to do it manually in thousands of posts.

Unfortunately I'm not very good with preg_replace so any help will be appreciated.

1
add_filter( 'the_content', 'wpse317670_add_img_attribute' ); 

function wpse317670_add_img_attribute( $content ) { 
    $from = '/'.preg_quote('<img', '/').'/';
    $to = '<img example="example"';

    return preg_replace($from, $to, $content, 1);
}

This will add the example="example" to the first image found in every post content.

There is another option, without using regular expression (possibly much faster and will use less memory):

add_filter( 'the_content', 'wpse317670_add_img_attribute' );

function wpse317670_add_img_attribute( $content ) {
    $from = '<img';
    $to   = '<img example="example"';

    $pos = strpos( $content, $from );
    if ( $pos !== false ) {
        return substr_replace( $content, $to, $pos, strlen( $from ) );
    }

    return $content;
}

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.