/ 设置 10 秒超时 // 每日统计清 0 runtime_set('todaycomments', 0); runtime_set('todayarticles', 0); runtime_set('todayusers', 0); if ($forumlist) { $fidarr = array(); foreach ($forumlist as $fid => $forum) { $fidarr[] = $forum['fid']; } forum_update($fidarr, array('todayposts' => 0, 'todaythreads' => 0)); } // 清理临时附件 attach_gc(); // 当天24点 $today = strtotime(date('Ymd')) + 86400; runtime_set('cron_2_last_date', $today, TRUE); // 往前推8个小时,尽量保证在前一天 升级过来和采集的数据会很卡 // table_day_cron($time - 8 * 3600); cache_delete('cron_lock_2'); } } } ?>Add attribute only to first image of every post via functions.php|Concepts Of Algorithm

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

admin2025-06-07  9

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;
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749230828a317459.html

最新回复(0)