功能中的Wordpress帖子标题 [英] Wordpress post title in functions
问题描述
我正在尝试将帖子标题设置为HTTP标头.我尝试了以下代码的多种变体(带有和不带有-> ID
选项),但没有任何输出,或者我得到了试图获取非对象的属性
错误:
is_admin()||add_action('send_headers',function(){全球$ post;$ title = get_the_title($ post-> ID);header('X-IC-Title:'.$ title);},1);
您的代码实际上非常接近.
如果您查看所有操作挂钩的
希望这会有所帮助!
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);
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!
这篇关于功能中的Wordpress帖子标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!