具有动态值的自定义 WooCommerce 端点不起作用

我想为 WooCommerce 创建一个具有动态价值的新端点。不幸的是我出错了rest_no_route。


这是代码(插件):


<?php 


function filter($data){

    $brand = $data['brand'];

    $products = [];

    $loop = new WP_Query( array(

        'post_type'      => 'product',

        'posts_per_page' => -1,

        'meta_query'     => array( array(

            'key'        => 'brands.id',

            'value'      => $brand,

            'compare'    => '=',

        )),

    ));

    if ( $loop->have_posts() ){

        while ( $loop->have_posts() ){

            $loop->the_post();

            array_push($products, get_post())

        } 

        wp_reset_postdata();

    }

    return $products;

    

}


add_action( 'rest_api_init', function () {

  register_rest_route( '/wc/v3', '/brand=(?P<brand>\d+), array(

    'methods' => 'GET',

    'callback' => 'brand',

  ) );

} );



?>

这就是我尝试访问的方式:


/wp-json/wc/v3/brand=1623

这是brand产品内部属性的样子:


"brands": [

            {

                "id": 1623,

                "name": "HUGO BOSS",

                "slug": "hugo-boss"

            }

        ],

感谢您的每一个帮助!


慕姐8265434
浏览 62回答 1
1回答

慕雪6442864

这是关于分类术语(不是发布元数据),特别是 WooCommerce 品牌,因此您需要使用税务查询,如下所示(假设您使用的是 WooCommerce 品牌,因此分类应为"product_brand")。所以你的函数应该WP_Query是:function filter($data){&nbsp; &nbsp; if( isset($data['brand']) && $data['brand'] > 0 ) {&nbsp; &nbsp; &nbsp; &nbsp; $taxonomy = 'product_brand'; // The taxonomy for WooCommerce Brands&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $products = (array) get_posts( array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'post_type'&nbsp; &nbsp; &nbsp; => 'product',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'post_status'&nbsp; &nbsp; => 'publish',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'posts_per_page' => -1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'tax_query'&nbsp; &nbsp; &nbsp; => array( array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'taxonomy'&nbsp; &nbsp; &nbsp; => $taxonomy,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'field'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;=> 'term_id',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'terms'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;=> intval($data['brand']),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ) ),&nbsp; &nbsp; &nbsp; &nbsp; ) );&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // return an array of WP_Post Objects (or an empty array)&nbsp; &nbsp; &nbsp; &nbsp; return $products;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;}它应该更好地工作。您应该使用自定义名称以不同的方式命名您的函数。
打开App,查看更多内容
随时随地看视频慕课网APP