自定义 Woocommerce 产品列表短代码

我正在尝试创建一个简单的自定义 Woocommerce 产品短代码,它将获得如下产品列表:

[custom_products_list ids='32,21,44,56']

并将输出带有 URL、标题、按名称排序和 ACS 的产品不需要其他信息,不需要缩略图或其他。就如上。我不想故意使用默认产品简码。

我将不胜感激任何帮助!提前致谢!


开满天机
浏览 128回答 1
1回答

慕慕森

像这样的东西...function custom_product_list_shortcode( $atts, $content = null ) {&nbsp; &nbsp; $_atts =&nbsp; shortcode_atts( [&nbsp; &nbsp; &nbsp; &nbsp; 'ids' => '',&nbsp; &nbsp; ], $atts );&nbsp; &nbsp; $ids_arr = array_filter( array_map( function( $id ){&nbsp; &nbsp; &nbsp; &nbsp; return trim( $id );&nbsp; &nbsp; }, explode( ',', $_atts['ids'] ) ) );&nbsp; &nbsp; $products = wc_get_products( [&nbsp; &nbsp; &nbsp; &nbsp; 'post_status' => 'publish',&nbsp; &nbsp; &nbsp; &nbsp; // can't remember if it's 'orderby' or 'order_by'&nbsp; &nbsp; &nbsp; &nbsp; 'order_by' => [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'title' => 'ASC',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'post_date' => 'DESC',&nbsp; &nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp; 'posts_per_page' => -1,&nbsp; &nbsp; &nbsp; &nbsp; // you can probably just pass in the comma sep string instead of array but maybe not.&nbsp; &nbsp; &nbsp; &nbsp; // you need to check that post__in is correct. look at the docs for WP_Query, or WC_Query, or wc_get_products()&nbsp; &nbsp; &nbsp; &nbsp; 'post__in' => $ids_arr,&nbsp; &nbsp; ]);&nbsp; &nbsp; // you could write your own sorting function like this if you want but you probably shouldn't need to&nbsp; &nbsp; // rsort( $products, function( $p1, $p2 ) {});&nbsp; &nbsp; // the html is for you to complete&nbsp; &nbsp; ob_start();&nbsp; &nbsp; ?>&nbsp; &nbsp; <div class="products-list">&nbsp; &nbsp; &nbsp; &nbsp; <?php foreach ( $products as $product ) { ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="product">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <pre>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?= print_r( $product, true ); ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?= get_title( $product->ID ); ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </pre>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <?php } ?>&nbsp; &nbsp; </div>&nbsp; &nbsp; <?php&nbsp; &nbsp; return ob_get_clean();}add_shortcode( 'custom_product_list', 'custom_product_list_shortcode' );
打开App,查看更多内容
随时随地看视频慕课网APP