Search code examples
phpwordpresscustom-wordpress-pages

How to change Wordpress WP_Post post_content and render via plugin?


I'm trying to build a dynamic page in Wordpress via a plugin. I have registered an action as follows:

add_action('the_post', 'createDynamicPage');

This works and the function is called as expected. I then receive the WP_Post object and check it like this:

public static function createDynamicPage(WP_Post $post)
{
    if (is_page('my-dynamic-page')) {
        // Do the processing etc
        $post->post_title = 'My New Title';
        $post->post_content = $whatIProcessedAbove;
    }
    return $post;
}

The change to the post_title property is reflected in the page, but the content is not.

So the solution I came up with was to modify the WP_Post object, pass it into wp_update_post() and then force the page to reload.

This works, and the page content is how it's supposed to be, but it's definitely not the right way to do it. For one, if someone else hits this page between my first hit, and the page reloading from the DB, I'll see their content.

So, how on Earth do I get the changes that I make to the post_content property to immediately be visible? Maybe I've used the wrong hook in add_action()???

Help!


Solution

  • OK, I was using the wrong hook. I actually needed to use filters instead

    First, register the filter on the the_content hook:

    add_filter('the_content', 'createDynamicContent');
    

    Now, modify the content in your page:

    public static function createDynamicContent(string $content)
    {
        if (is_page('my-dynamic-page')) {
            // Do the processing etc
            $content = $whatIProcessedAbove;
        }
        return $content;
    }
    

    Couldn't see the wood for the trees!