Wordpress:根据 URL 参数过滤帖子自定义字段值

Wordpress: Filter Posts Custom Field Value Based on URL Parameter

我在名为 Advanced Custom Field 的插件的帮助下为我的每个 post 添加了自定义 'checkbox' 字段。字段名称是 'country',根据插件作者的说法,

在新的 line.For 更多控件上输入每个选项,您可以像这样同时指定值和标签: 红色 : 红色 蓝色 : 蓝色

我自己的值和标签是这样的:

美国:美国

FR:法国

现在,我想根据 'country' 字段值过滤 post。所以当URL是这样的example.com?country=us时,它应该显示所有与美国相关的post。

我将以下代码添加到我的 functions.php 但它不起作用。

function my_pre_get_posts( $query ) {

// do not modify queries in the admin
if( is_admin() ) {

    return $query;

}

if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post')) {

    // allow the url to alter the query
    if( isset($_GET['country']) ) {

        $query->set('meta_key', 'country');
        $query->set('meta_value', $_GET['country']);

    } 

}


// return
return $query;

}

说到 PHP,我是菜鸟。我做错了什么?

更新:

当我第一次尝试时,它根本不起作用。当我尝试登录我的管理页面时。我收到另一个错误:

Xdebug: Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in \wp-content\themes\functions.php on line 14

第14行的代码是

if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post'))

错误消息准确地告诉您问题出在哪里... 你Cannot use isset() on the result of an expression在行if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post'))

代码无效,因为第 14 行中的 if 语句无法正确求值。

isset 将一个变量(或多个变量)作为其参数 - 您在 if 语句的整个表达式中传递它,这是不允许的。您使用 isset 检查变量是否已设置且不为 NULL ,然后 检查它是什么 Ref: http://php.net/manual/en/function.isset.php

您需要将代码的第 14 行更改为以下内容:

if( 
    isset($query->query_vars['post_type']) // check if the post_type query var has a value
    &&                                     // AND if it does...
    $query->query_vars['post_type'] == 'post'  // ... only then check if its == "post"
) 

它可以和你的例子在同一行(只要你删除评论)...我只是把它分开来突出你正在评估的表达式的不同部分。