What is best practices to move the following code into a function?

I’m going to add numbers here to make this more clear. Even as I read it, knowing what each piece means, it can be semantically disorienting.

Your original function is calling (1)$post->post_content from the object and, depending on the conditional, echoing something or echoing what is returned in the function (2)the_content(), which is just (1)$post->post_content after it has run through (3)get_the_content() and (2)the_content().

When you look at the source of (3)get_the_content() you can see what is happening to (1)$post->post_content before it gets to (2)the_content()

Your second function is receiving (1)$post->post_content after it has run through (3)get_the_content(), into (2)the_content() and then applying changes on it before it is echoed.

The (4)apply_filters('the_content'... you are hooking with your (5)add_filter('the_content'... is at line 240 of post-template.php at the end of the function (2)the_content() that is calling the function (3)get_the_content() that is retrieving (1)$post->post_content from the current $post object.

(It’s less content, content, content sounding when looking at each piece)


For your second function, you need to return (6)$content if you want there to be content for the function (2)the_content() to display. In your template you would just use (2)the_content(), as your conditional is being applied (by (4)apply_filters('the_content'... just before (2)the_content() returns.

I would add an if ( [is_page()][3] && [is_main_query()][3] ) {} wrapper inside your second function as well, so it isn’t applied to non-page loops or sub-queries, as you need.

BUT the thing to check first, in my opinion, is to alter your original function so it uses (3)get_the_content() instead of (1)$post->post_content to be sure you can hook after that function has done its thing (which is what you are doing now) without losing your intended results.

Man I hope that’s clear.

Look at the links to see the relation between each. It will really, really, help to understand each piece so you know where you are in the chain of events, and why you are hooking here or there etc.