【问题标题】:Query product title or slug based on shortcode atts name in Woocommerce根据 Woocommerce 中的简码 atts 名称查询产品标题或 slug
【发布时间】:2018-08-24 13:01:10
【问题描述】:

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

【问题讨论】:

    标签: php wordpress woocommerce shortcode product


    【解决方案1】:

    更新:

    要通过 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

    【讨论】:

    • 是的,看起来可能还有其他问题,因为无论使用title 还是name,都返回了相同的产品。我以前看到过这个,并认为我做错了什么。假设在插件和functions.php中定义它应该没有区别。
    • 如果您使用“名称”查询产品标题,它会起作用,因为标题在内部使用sanitize_title_for_query() 函数进行了清理,这可能就是原因。如果已发布的答案正在回答您的问题,请不要忘记接受答案。谢谢。
    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 2014-04-29
    • 2022-01-02
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2014-09-20
    相关资源
    最近更新 更多