Wordpress post title in functions

被刻印的时光 ゝ 提交于 2020-01-07 06:51:34

问题


I'm attempting to set the post title as a HTTP header. I've tried a number of variations of the below code (with and without the ->ID option) and nothing outputs or I get an Trying to get property of non-object in error:

is_admin() || add_action('send_headers', function(){
    global $post;
    $title = get_the_title($post->ID);
    header('X-IC-Title:' . $title);
}, 1);

回答1:


Your code is actually very close.

If you take a look at this list of all of your action hooks, you'll see that the send_headers action occurs before the Wordpress object is completely set up.

What this means is that the usual objects and functions that reference the Wordpress globals won't work at this point in the lifecycle. You actually have to hook into the core a little bit later so that you can retrieve Post-related data.

I'm not sure why you have the is_admin() || check prefixing your action hook. add_action returns a call to add_filter (Source), which in turn returns a boolean value of true (Source).

Short-circuiting wouldn't be of any use to you here, so I've modified your code to the following:

add_action('wp', function(){
    global $post;
    $title = get_the_title($post->ID);
    header('X-IC-Title:' . $title);
}, 1);

I've tested this in a clean Bedrock installation on a Homestead server and I'm seeing the new header in my network output(screenshot attached).

Hopefully this helps!



来源:https://stackoverflow.com/questions/40099625/wordpress-post-title-in-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!