wordpress - 为什么 $wp_query->post 在 404 期间未设置?

标签 wordpress

我正在使用一个名为 Connections 的插件。当 404 发生时(有充分的理由,即通过浏览器访问不存在的页面),则在插件代码中指定的自定义后回调过滤器将中断,如 $wp_query->post未设置。当访问 $wp_query->post->ID 时,我们收到投诉 尝试获取非对象的属性。正如您所期望的。

我已禁用所有其他插件并返回“二十十五”主题,但问题仍然出现。全新安装时不会出现此问题。这对我来说没有意义。如果不是插件或主题问题,并且不在 WordPress 核心中,那么问题出在哪里?数据库损坏? (其他一切似乎都工作正常)。

过滤器回调在这里:

public static function filterPostTitle( $title, $id = 0 ) {
   global $wp_query, $post, $connections;

   // ADDED: If I add this line the problem goes away.
   if ( is_404() ) return $title;

   // Whether or not to filter the page title with the current directory location.
   if ( ! cnSettingsAPI::get( 'connections', 'connections_seo', 'page_title' ) ) return $title;

   // If I uncomment the next two lines and comment out the following line of code, then the problem also goes away.
   //$post_id = get_queried_object_id();
   //if ( ! is_object( $post ) || $post_id != $id || ! self::$filterPermalink ) return $title;

   if ( ! is_object( $post ) || $wp_query->post->ID != $id || ! self::$filterPermalink ) return $title;

如果我在函数的开头添加以下检查,那么问题也会消失(再次正如我们所期望的那样):

if ( ! isset( $wp_query->post ) || ! isset( $wp_query->post->ID ) ) return $title;

我已经打印出回溯来给我提供线索,但是回溯似乎没有提供太多线索,因为全局变量 $wp_query 有问题。这再次提醒我们为什么全局变量是不好的做法……对于 WordPress 来说这是一场非常糟糕的表演。全局变量使调试成为一场噩梦。全局变量在哪里改变了?我们不知道。

过滤器回调设置如下:

add_filter( 'the_title', array( __CLASS__, 'filterPostTitle' ), 10, 2 );

插件的开发人员(也许是这样)认为问题出在他的插件之外。

问题: 为什么 $wp_query->post 在触发回调时未设置? $wp_query->post 是否应该始终在触发“the_title”过滤器回调时设置?

正如您可能猜到的那样,我对 Wordpress 相当陌生。这非常棒……不过,我不喜欢全局变量……这是一个很大的禁忌。

最佳答案

这并不是说 $wp_query->post 在 404 期间未设置...而是它根本就没有设置过。事实上,在初始化时,$wp_query->post 对于 WP_Query 的所有新实例都未设置。让我们look at the source :

/**
 * Initiates object properties and sets default values.
 *
 * @since 1.5.0
 * @access public
 */
public function init() {
    unset($this->posts);
    unset($this->query);
    $this->query_vars = array();
    unset($this->queried_object);
    unset($this->queried_object_id);
    $this->post_count = 0;
    $this->current_post = -1;
    $this->in_the_loop = false;
    unset( $this->request );
    unset( $this->post );  // Always unset
    unset( $this->comments );
    unset( $this->comment );
    $this->comment_count = 0;
    $this->current_comment = -1;
    $this->found_posts = 0;
    $this->max_num_pages = 0;
    $this->max_num_comment_pages = 0;
    $this->init_query_flags();
}

接下来是 query is parsed ,如果出现错误:

if ( '404' == $qv['error'] )
    $this->set_404();

404 状态已设置,并且 $wp_query->post 从未填充/设置。

关于wordpress - 为什么 $wp_query->post 在 404 期间未设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33283211/

相关文章:

jquery - 仅当 Woocommerce 结帐字段可见时才需要

wordpress - Tax_Query 不适用于 WP_Query

php - 从 WordPress 插件添加的脚本和样式标签中删除类型属性

php - PayPal IPN 反复运行

php - Ajax 调用 php 脚本返回 404 错误

php - 如何判断脚本是否从 WordPress 中的插件、主题或子主题执行?

php - 来自外部来源的 Woocommerce 更新价格

php - Wordpress 如何读取评论标题?

css - 带有侧边栏和响应式图像和文本的两列布局

php - 如何在 URL WooCommerce 中删除/购物或/产品