You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为WordPress短码添加多值属性?以order属性为例

解决WordPress短码支持order属性的方案

没问题,我帮你调整代码,让短码支持传入order属性来控制排序方向。主要需要做这几步:设置短码默认属性、验证传入的排序值,再把它应用到WP_Query里。

修改后的完整代码

function review_category_func($atts) {
    // 定义短码默认属性
    $default_atts = array(
        'id' => '',
        'posts_per_page' => -1, // 默认显示所有符合条件的文章,可根据需求修改
        'tag' => '',
        'order' => 'desc' // 默认排序方向为降序
    );

    // 合并用户传入的属性和默认属性
    $atts = shortcode_atts($default_atts, $atts);

    $taxID = intval($atts["id"]);
    $ppp = intval($atts["posts_per_page"]);
    $output = '';

    // 处理排序方向:确保值只能是asc或desc
    $order = strtolower($atts['order']);
    if (!in_array($order, array('asc', 'desc'))) {
        $order = 'desc'; // 非法值时使用默认值
    }

    $args = array(
        "post_type" => "reviews",
        "posts_per_page" => $ppp,
        'tax_query' => array(
            array(
                'taxonomy' => 'review_category',
                'field' => 'term_id', // 修正:原代码的'id'是错误参数名,应该用'field'
                'terms' => $taxID
            )
        ),
        'orderby' => 'taxonomy_cat',
        'order' => $order // 使用处理后的排序方向
    );

    if (isset($atts['tag']) && !empty($atts['tag'])) {
        $terms = explode(',', $atts['tag']);
        $args['tax_query']['relation'] = 'AND';
        $args['tax_query'][] = array(
            'taxonomy' => 'review_sources',
            'field' => 'term_id', // 同样修正参数名
            'terms' => $terms
        );
    }

    $qry = new WP_Query( $args );

    // 你的后续代码(循环输出内容等)
    if ($qry->have_posts()) {
        while ($qry->have_posts()) {
            $qry->the_post();
            // 这里添加你的输出逻辑,比如the_title(), the_content()等
            $output .= '<h3>' . get_the_title() . '</h3>';
        }
    } else {
        $output .= '<p>No reviews found.</p>';
    }

    wp_reset_postdata(); // 注意:推荐用wp_reset_postdata()代替wp_reset_query(),因为这里用的是WP_Query而非query_posts
    return $output;
}
add_shortcode("review_category", "review_category_func");

关键修改说明

  • 默认属性处理:用shortcode_atts()统一管理短码的参数,既保证默认值的存在,又能正确接收用户传入的order、id等参数
  • 排序值验证:通过strtolower()和in_array()确保传入的order值只能是asc或desc,避免非法参数导致查询出错
  • 修正tax_query参数:原代码中tax_query里的'id' => 'term_id'是错误的,WP_Query要求用'field'指定匹配的字段类型,所以改成'field' => 'term_id'才能让分类查询正常工作
  • 替换固定排序值:将原来硬编码的'order' => desc改成使用处理后的$order变量,实现动态控制排序方向

现在你就可以在短码中像这样使用了:
[reviews_category id=1 tag=25 order=asc] 或者 [reviews_category id=1 order=desc]

内容的提问来源于stack exchange,提问作者Mario83

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:40:10