2

I am trying to allow a plugin to modify the rendered content of posts prior to it being rendered for the WP API, or at least save it as a separate property on that JSON response.

For instance, imagine a plugin that changes the content of a post from

Here is some content : foo

to

Here is some content : bar

It's setup to use the the_post filter to make its modifications for the frontend. But the REST api is unaffected. I have tried using the rest_prepare_post filter but it's (a) apparently a bad practice to modify the rendered content directly, so I'd put it as an additional property? and (b) difficult to work with -- if I so much as try to assign $data->$data['content']['rendered'] to a variable I get the message that I am trying to convert a WP Rest response object to a string. Yet if I output that same variable to my error log, it works fine.

add_filter( 'rest_prepare_post', array( __CLASS__, 'beforeFilterRest' ), 0, 2 );

public static function beforeFilterRest( $data, $post ){

            $old_rendered_content = $data->$data['content']['rendered'];
            $data->$data['content']['rendered'] = preg_replace_callback(
                "/\s*<pre(?:lang=[\"']([\w-]+)[\"']|line=[\"'](\d*)[\"']|escaped=[\"'](true|false)?[\"']|highlight=[\"']((?:\d+[,-])*\d+)[\"']|src=[\"']([^\"']+)[\"']|\s)+>(.*)<\/pre>\s*/siU",
                array( __CLASS__, 'substituteToken' ),
                $old_rendered_content
            ); 
            return $data;
    }

I get an error right at the first line of that function. What am I missing?

2

It looks to me like you've written $data->$data[...] where you mean to have $data->data[...]. The "object to string" conversion error is probably due to the second $data, where PHP expects an object's property name but is getting another reference to the $data object.

| improve this answer | |
  • 2
    Let's never speak of this again.. – tmdesigned Sep 16 '18 at 8:48
  • I once wrote a the_content filter that blanked every page but the one I was trying to filter. In the end I discovered that my return $content; line was only happening where my condition matched (ie, it was inside the if() statement). An easy fix, but I spent five solid hours barking up all the wrong trees before I noticed my mistake. – Pat J Sep 16 '18 at 16:56

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.