为什么我的 WP_Query 找不到一个结果?

Why does my WP_Query not find one result?

我有一个我写的插件,除了一个功能外,它对所有功能都非常有效。不太有效的是当我在 REST API 函数中执行 WP_Query 时,它看起来像这样:

  $args = array(
    'post_type' => 'download',
    'post_status' => 'publish',
    'posts_per_page' => 100,
    'paged' => $request['id']
  );

  $posts = new WP_Query( $args );

它正确地 returns 每个 post_type 类型 download 除了一个永远不会包含在结果中的。如果我使用 get_post( 1256 ) 然后我得到以下内容:

{
    "ID": 1256,
    "post_author": "1",
    "post_date": "2021-06-17 09:57:06",
    "post_date_gmt": "2021-06-17 08:57:06",
    "post_content": "An example: hello world",
    "post_title": "My Ticket",
    "post_excerpt": "",
    "post_status": "publish",
    "comment_status": "closed",
    "ping_status": "closed",
    "post_password": "",
    "post_name": "my-ticket",
    "to_ping": "",
    "pinged": "",
    "post_modified": "2021-06-17 10:28:08",
    "post_modified_gmt": "2021-06-17 09:28:08",
    "post_content_filtered": "",
    "post_parent": 0,
    "guid": "https://www.example.com/my-ticket",
    "menu_order": 0,
    "post_type": "download",
    "post_mime_type": "",
    "comment_count": "0",
    "filter": "raw"
}

这看起来我的查询是正确的,应该返回这个 post,即它是正确的下载 post_type 并且是发布的 post_status。

我不明白为什么我的查询不起作用。我错过了什么或者是否有其他过滤器可以阻止它被退回?

正如您在评论中提到的那样。

You were correct. AND wp_posts.ID NOT IN (1256) is in the SQL. How can I query my data correctly? I can't turn off the plugins, I just want to control my own data.

由于我没有插件代码,我会尝试解释如何绕过 post id 的排除。

假设这是排除 post.

的代码
add_action('pre_get_posts','alter_query');

function alter_query($query) {
    $query-> set('post__not_in' ,array(33));
}

也可能有其他操作会触发此排除。

如果您使用以下函数获取代码。

function get_data() {
    $args = array(
        'post_type' => 'page',
        'post_status' => 'publish',
        'posts_per_page' => 100,
    );

    $posts = new WP_Query( $args );

    return $posts;
}

var_dump(get_data());

然后你就可以像这样去掉排除了。

function get_data() {
    // Remove the removal action
    remove_action( 'pre_get_posts', 'alter_query' );
    $args = array(
        'post_type' => 'page',
        'post_status' => 'publish',
        'posts_per_page' => 100,
    );

    $posts = new WP_Query( $args );

    // Add the removal action back.
    add_action( 'pre_get_posts', 'alter_query' );

    return $posts;
}

这样您就不会真正更改插件的任何代码,您只是在需要 运行 代码时将其关闭。

This is just an example you would want to change it according to your own situation.

正在查找导致问题的操作代码。

  1. 安装 Query Monitor 插件并激活它。

  2. 运行 您在特定页面上的查询并以管理员登录访问该页面。您将在管理栏上看到查询监视器选项卡。

  3. 单击它打开 select 挂钩和操作。

  4. 在挂钩列中搜索 (ctrl + f)“pre_get_posts”。这是在 pre_get_posts 仅用于更改查询的条件下。

  5. 找到 的实例后,您可以检查函数的名称。在这种情况下:alter_query() 和位置 wp-content/themes/storefront/functions.php:113

Once you have the function name you remove and add the action as shown above. remove_action( 'pre_get_posts', 'alter_query' );