Introducing how to insert images or text immediately after H2 tags in WordPress. You can insert different images for each category and various other extensions are possible, so please master it.
Benefits
The reason I’m doing this is that I have a hypothesis about SEO: “how much scrolling occurred”. I think it definitely exists, and I also think it’s a fairly large proportion.
Also, user dwell time is said to be important. This is well known.
Scrolling means the dwell time extends by that amount. Looking at ads, looking at images - these split-second times are important.
How much is it designed to not let users go - this is the key point.
Regular Expression Replacement in PHP
To do regular expression replacement in PHP, I think executing the following code would be quick.
<?php
$string = 'aaa</h2>aaa';
$pattern = '/(<\/h2>)/i';
$replacement = '$1aiu';
$return .= preg_replace($pattern, $replacement, $string) ;
echo $return;
In WordPress, we replace the entire body text, so change $string = 'aaa</h2>aaa'; to $string = $the_content;. That’s the only difference.
This was my first time writing regular expressions in PHP, but regular expression replacement is a bit harder to write compared to Ruby. Ruby can be written concisely with grep.
Test in WordPress
Write the following code in function.php and update the site.
function category_1_1($the_content) {
if (is_single() && in_category(array('ゲーム'))) {
$string = $the_content;
$pattern = '/(<\/h2>)/i';
$replacement = '$1aiu';
$return .= preg_replace($pattern, $replacement, $string) ;
return $return;
} else {
return $the_content;
}
}
add_filter('the_content','category_1_1');
Now the string “aiu” should be added after H2 in articles in the “ゲーム” (Game) category.
Inserting Images
Now, let’s get to the main topic - inserting images. It’s simple. Just write the img tag HTML.
function category_image_1($the_content) {
// if (is_single() && in_category(array('プログラミング'))) {
$string = $the_content;
$pattern = '/(<\/h2>)/i';
$replacement = '$1

';
$return .= preg_replace($pattern, $replacement, $string) ;
return $return;
// } else {
// return $the_content;
// }
}
add_filter('the_content','category_image_1');
As an example, please look at the code I wrote for this site.
On this site, I stopped changing images by category. It’s quite troublesome.
Don’t forget to write the alt tag too.
Inserting After H1 Tags
I tried to insert after H1 tags, but for some reason I couldn’t insert right after h1. Even looking at the source, there’s no change, and the code isn’t wrong… I didn’t want to spend more time on this, so I gave up. It’s a mystery…
Depending on the theme, this kind of thing might happen.