我正在尝试将帖子标题设置为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帖子标题
发布评论