Modifying post content with the_post action hook
Don’t use the_post
, instead use the_content
filter to modify content passed to the the_content()
call.
However, this is your theme, so the best way to do this is to just do it in search.php
, and not bother with the filters and actions. AKA don’t run the code on a filter to try and modify or intercept what the template is doing, just do it directly in the template.
E.g. if this is my search.php
:
<?php
while( have_posts() ) {
the_post();
the_title();
the_content();
}
And I want to replace the content with Lorem ipsum, I can do this:
<?php
while( have_posts() ) {
the_post();
the_title();
?>
<p>Lorem Ipsum Dolors sit atem etc....</p>
<?php
}
Or if I wanted to add a PNG advertisement for ponies after every title in search results:
<?php
while( have_posts() ) {
the_post();
the_title();
toms_pony_advert();
the_content();
}
Where the function toms_pony_advert()
outputs said advertisement.
I suspect you’re hung up on there being some magical WordPress way to modify the theme template without actually modifying the theme template, but the correct way is to just modify the file directly. After all it is your code. It isn’t to use some sort of filter or action, or API. The reason you couldn’t find this via searching is because it isn’t WordPress knowledge, it’s fundamental programming knowledge, specifically PHP fundamentals.
If it isn’t your code though, then create a child theme and do it that way. If it’s WP Core, no, never do that, use actions and filters. If it’s somebody elses plugin use actions and filters, and if there are none, tough, you’ll have to request they be added or fork the plugin
If you were trying to do this from a plugin, and in such a way that it did it worked for all themes on the other hand, that would be an entirely different problem, and one that has no proper solution. But you are not in that situation.