您尚未说明选择的工作方式,但在选择特定月份和年份存档时,需要设置某种条件。我也不知道在哪里get_the_time
输入或其与查询的相关性。
但不管怎样,我还想讨论一些其他真正重大的问题。您正在使用URL中的未清理输入值。这确实是一个巨大的安全风险,也是黑客用来攻击你网站的头号攻击点之一。GOLDEN RULE: NEVER EVER 信任来自任何地方或任何人的任何输入值,甚至不信任您自己。在您的示例中,很容易将恶意代码传递给category
参数,并且由于您不验证和转义它,此代码可以自由执行任何操作,一个黑客会跳上跳下,因为他破坏了另一个站点
代替使用$_GET[\'category\']
, 您可以简单地使用filter_input
它验证参数并返回值或false
如果未设置参数。您还可以通过过滤器的第三个参数对输入进行清理。因为这是一个弹头,我们将使用FILTER_SANITIZE_STRING
当您创建tax_query
, 您不需要设置relation
此外,默认值为AND
, 所以您不需要设置它
您还需要根据条件设置参数。以下是您的代码示例:(Note: 这是未经测试的,需要PHP 5.4+)
<?php
$category_slug = filter_input(
INPUT_GET, // Global variable to use, in this case it will be a $_GET variable
\'category\', // Name or the parameter to get value from
FILTER_SANITIZE_STRING // Use the FILTER_SANITIZE_STRING filter to sanitize the returned value
);
// Check if $category_slug has a vlaue, if so, set the tax_query
$cat_area_query = [];
if( $category_slug ){
$cat_area_query = [
[
\'taxonomy\' => \'category\',
\'field\' => \'slug\',
\'terms\' => $category_slug // No need to sanitize, the value is already sanitized
// The operator is set to IN by default
]
];
}
$date_query = [];
// I have kept the month and year values the same as in your question though I doubt if this is correct
$m = filter_var( get_the_time( \'m\' ), FILTER_VALIDATE_INT ); // Sanitize and validate value as an integer
$y = filter_var( get_the_time( \'Y\' ), FILTER_VALIDATE_INT ); // Sanitize and validate value as an integer
if ( \'some_condition_for_month\' ) {
$date_query = [
[
\'year\' => $y,
\'month\' => $m
]
];
} elseif ( \'some_condition_for_year\' ) {
$date_query = [
[
\'year\' => $y,
]
];
}
$args = [
// The post_type and post_status parameters are set by default to \'post\' and \'publish\'
// orderby \'date\' is default
\'order\' => \'desc\',
\'tax_query\' => $cat_area_query,
\'date_query\' => $date_query
];
$posts_query = new WP_Query( $args );
?>