I try to change something my wordpress page. I'm always writing contect with h3 tag but mutiple like each post 3 times 3h.

I want to add some text after first h3 tag.

function add_content_after_h3($content){
    if (is_single()) {
        $div = '<div>sometext</div>';
        $content = preg_replace('/(<\/h3>)/i', '\1'.$div, $content);

    return $content[0];

add_filter('the_content', 'add_content_after_h3');

But this code not working :(


Note returning $content[0]; when !is_single() you'll get non-exist errors.

You can accomplish what you're after with somthing like:

add_filter('the_content', function ($content){
    if (!is_single()) return $content;
    $div = "🎅🏻";
    return preg_replace('/<\/h3>/i', "</h3>".$div, $content, 1);

note the third parameter of preg_replace() is the limit, setting to 1 will restrict the replace to the first match.

  • if i want put something not after before do you have some idea for this ? – ZgrKARALAR Dec 14 '17 at 22:17
  • for before? then preg_replace('/<h3/i', $div."<h3", $content, 1); – David Sword Dec 14 '17 at 23:05

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.