此代码手动设置订单\'order\' => \'ASC\'
WP\\u查询参数中的声明。
$loop = new WP_Query( array(
\'post_type\' => \'product\',
\'meta_key\' => \'product_price\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'ASC\',
\'posts_per_page\' => 4,
\'paged\' => $paged) );
如果要将url参数传递给该参数,可以使用如下内容:
\'order\' => $_GET[\'posts_order\']
以及url模式,如:
/?posts_order=ASC
但那将是一个可怕的想法。。。因为有人可以访问url:/?posts_order=DROP TABLE IF EXISTS table1
&;可能会破坏事物。
因此,如果我们要侦听url中的变量,我们需要对其进行清理。
<?php
if ( ! empty( $_GET[\'posts_order\'] ) ) {
$posts_order = sanitize_key( $_GET[\'posts_order\'] ); // prevent malicious characters in user-submitted variable
}
或者,更好的是,我们可以使用白名单方法&;仅允许的某些值
$posts_order = \'DESC\';
if ( ! empty( $_GET[\'posts_order\'] ) ) {
$posts_order_raw = sanitize_key( $_GET[\'posts_order\'] );
if ( \'ASC\' === $posts_order_raw ) {
$posts_order = \'ASC\';
}
}
$loop = new WP_Query( array(
\'post_type\' => \'product\',
\'meta_key\' => \'product_price\',
\'orderby\' => \'meta_value_num\',
\'order\' => $posts_order,
\'posts_per_page\' => 4,
\'paged\' => $paged) );
但是等等,还有更多!
我们可以从WP\\u查询中完全省略订单声明
$loop = new WP_Query( array(
\'post_type\' => \'product\',
\'meta_key\' => \'product_price\',
\'orderby\' => \'meta_value_num\',
// \'order\' => $posts_order, # Remove this line #
\'posts_per_page\' => 4,
\'paged\' => $paged) );
&;相反,从
pre_get_posts
挂钩:
<?php
function wp_se_331547( $wp_query ) {
if ( !is_admin() && is_main_query() ) {
if( \'product\' === get_post_type() ) {
$posts_order = \'DESC\';
if ( ! empty( $_GET[\'posts_order\'] ) ) {
$posts_order_raw = sanitize_key( $_GET[\'posts_order\'] );
if ( \'ASC\' === $posts_order_raw ) {
$posts_order = \'ASC\';
}
}
$wp_query->set( \'order\', $posts_order );
}
}
}
add_action(\'pre_get_posts\', \'wp_se_331547\');