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

时间:2018-03-15 16:05:52

标签: php wordpress woocommerce shortcode product

我想通过它的标题或名称(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 ) :

1 个答案:

答案 0 :(得分:1)

更新:

要按 slug 查询产品,请使用 "name" 参数或标题,使用 "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