Hooking the_content filter in wordpress

2019-04-17 02:01发布

I'm saving the post content into a post meta, and I'd like to retrieve it instead of the original post content so that when I call the_content() the data in the post meta appears not the actual post data.

function test(){
    $post_meta = post meta data here ....
    echo apply_filters('the_content', '$post_meta');
}
add_filter('the_content', 'test');

I'm getting this error

Fatal error: Maximum function nesting level of '100' reached

The error does make sense, but how can I achieve what I'm trying to do, any ideas?

标签: php wordpress
2条回答
Melony?
2楼-- · 2019-04-17 02:28

I think you want to add your filter before the_content() is even called. You probably want something like this.

function modify_content() {
    global $post;
    $post_meta = 'testing';
    $post->post_content = $post_meta;
}
add_action('wp_head', 'modify_content');

This would allow you to modify the contents of the post and still run it through the filters on the_content(). Though this will only work for single posts/pages. You will have to find another hook if you want to alter the archive pages too.

查看更多
甜甜的少女心
3楼-- · 2019-04-17 02:43

UPDATE: After much banging my head against the wall, here is the best way I can think of to hook into the_content and use its filter from within the custom callback without falling into an infinite loop.

The answer was surprisingly simple, and I feel silly for not thinking of it before:

function test($content)
{
    remove_action('the_content', 'test'); //DISABLE THE CUSTOM ACTION
    $post_meta = post meta data here ....
    $cleaned_meta = apply_filters('the_content', $post_meta);
    add_action('the_content', 'test'); //REENABLE FROM WITHIN
    return $cleaned_meta;
}
add_action('the_content', 'test');

I'm sure you've found another solution by now, but still, I hope this helps with any issues you might run into in the future.

查看更多
登录 后发表回答