wordpressglobal$post返回null,但可以与其他过滤器一起使用


wordpress global $post returns null, works with other filters though

我正试图使用post->ID保存一个post元,但$post似乎为空,并显示notice-"notice:trying to get property of non-object"(访问$post->ID时)

因此add_filter似乎根本不起作用。

add_filter('add_to_cart_redirect', array($this, 'custom_add_to_cart_redirect')); // Goes in class constructor.

function custom_add_to_cart_redirect() {
    global $post;
    var_dump($post).die();      // this $post var is always null.
    return $this->woocommerce_custom_add_to_cart_get_cartURL(); // The global $post declaration within this method doesn’t works too.
}

我还尝试在全局声明之前添加wp_post_resetdata()调用,但没有成功。

知道这里出了什么问题吗?

我今天遇到了类似的情况,全局$post在本应使用的时候却不可用。经过仔细检查,我发现is_404()的每个页面请求都返回true,因此对post0的查询未能返回全局$post对象的数据。

Flushing permalinks帮了我一把(没什么了不起的,我只是重新保存了它们)。

您可以使用类似的wooccommerce全局变量

global $woocommerce;
var_dump($woocommerce).die();

您是否在外部PHP脚本中加载上述代码?您可能需要包含wp_load.php