最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Add attribute only to first image of every post via functions.php

matteradmin9PV0评论

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.

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.

Share Improve this question asked Oct 26, 2018 at 9:21 k8310k8310 31 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 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;
}
Post a comment

comment list (0)

  1. No comments so far