admin管理员组文章数量:1122846
I am trying to get the post id outside the loop in functions.php.but what error i am getting : Notice: Trying to get property of non-object in functions.php on line 549
function theme_myeffecto_disable() {
global $wp_query;
$post_id = $wp_query->post->ID;
$showreaction = get_post_meta( $post_id, 'post_reaction_show', true );
$showreaction = isset($showreaction) ? $showreaction : true;
var_dump($showreaction);
}
add_action( 'init', 'theme_myeffecto_disable', 20 );
and $showrating
always comes false weather it is true or false :(
I am trying to get the post id outside the loop in functions.php.but what error i am getting : Notice: Trying to get property of non-object in functions.php on line 549
function theme_myeffecto_disable() {
global $wp_query;
$post_id = $wp_query->post->ID;
$showreaction = get_post_meta( $post_id, 'post_reaction_show', true );
$showreaction = isset($showreaction) ? $showreaction : true;
var_dump($showreaction);
}
add_action( 'init', 'theme_myeffecto_disable', 20 );
and $showrating
always comes false weather it is true or false :(
3 Answers
Reset to default 0You can not get post ID in init
hook. The first safe hook to get post id is template_redirect
.
See this answer for more details:
you could simply just add this in your template
<?php
global $post;
if($post >= 1) {
echo $post->ID;
}
?>
or if you want it in your functions.php and use it any where
function get_my_post_id() {
global $post;
if($post >= 1) {
echo $post->ID;
}
}
add_shortcode( 'post_id', 'get_my_post_id' );
// then add the shortcode in your template file where you want the post_id output
<?php echo do_shortcode('[post_id]'); ?>
Rizwan Mention before you can't use init
hook for this. The first hook that is safe to get post id is template_redirect
. Here you can see details. I've used get_queried_object_id() to get current post id.
add_action('template_redirect', function () {
$post_id = get_queried_object_id();
// if post id available, this will not execute in archive pages.
if ($post_id) {
$showreaction = get_post_meta($post_id, 'post_reaction_show', true);
$showreaction = isset($showreaction) ? $showreaction : true;
var_dump($showreaction);
}
});
本文标签: functionsGet post id outside loopNotice Trying to get property of nonobject
版权声明:本文标题:functions - Get post id outside loop : Notice: Trying to get property of non-object 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736281238a1926255.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
init
action, it's too early. – Milo Commented Sep 12, 2017 at 15:33