根据 Woocommerce 中的短代码 atts 名称查询产品标题或 slug

Query product title or slug based on shortcode atts name in Woocommerce

我想通过标题或名称 (slug) 查询产品。下面的代码将允许我检索带有特定标签的产品,但是当我尝试使用 pagepagename 而不是 product_tag 时,没有返回任何产品。除非我忽略了它,否则我没有看到相关的 product_page 或类似内容。感谢您深入了解我可能哪里出错了。

function woo_products_by_name_shortcode( $atts, $content = null ) {

        // Get attributes
        extract(shortcode_atts(array( "tags" => '' ), $atts));

        ob_start();
        // Define Query Arguments
        $args = array(
                                //'post_type'    => array('product','product_variation'),
                                'post_type'    => 'product',
                                'posts_per_page' => 5,
                                'product_tag'    => $tags
                                );

        // Create the new query
        $loop = new WP_Query( $args );

        // Get products number
        $product_count = $loop->post_count;

        // If results
        if( $product_count > 0 ) :

更新:

要通过 slug 查询产品,请使用 "name" 参数或通过 title 使用 "title" 参数:

function woo_products_by_name_shortcode( $atts, $content = null ) {

    // Get attributes
    extract( shortcode_atts( array( 
        'tags' => '',
        'name' => ''
        'title' => ''
    ), $atts ));

    ob_start();

    // Define Query Arguments
    $loop = new WP_Query( array(
        'post_type'      => 'product',
        'post_status'    => 'publish',
        'posts_per_page' => 5,
        'product_tag'    => $tag,
        'name'           => $name,
        'title'          => $title
    ) );

    // Get products number
    $product_count = $loop->post_count;

    // Test raw output
    echo '<pre>'; print_r($loop->posts); echo '</pre>'; 

已测试并有效

官方文档:WP_query - Post and page parameters