Advertisement
lorro

WooCommerce - List products with availability

Jan 12th, 2017
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.23 KB | None | 0 0
  1. <?php
  2.   // Shortcode to make a list of products from a category
  3.   // usage: [products_list rows="-1" category="kits" orderby="title" order="ASC"]
  4.   // rows defaults to -1, show all products
  5.   // category defaults to '', empty: shows all categories, value: category slug
  6.   // orderby defaults to 'title'
  7.   // order defaults to 'DESC'
  8.   // for orderby options see: https://codex.wordpress.org/Template_Tags/get_posts
  9.   // code goes in functions.php for your child theme
  10.  
  11.   add_shortcode('products_list', 'products_list');
  12.   function products_list( $atts ) {
  13.     global $post;
  14.     // get the parameters
  15.     $args = shortcode_atts( array(
  16.       'rows'            => -1,
  17.       'category'        => '',
  18.       'tag'             => '',
  19.       'orderby'         => 'title',
  20.       'order'           => 'ASC'
  21.       ), $atts );
  22.     $rows = (int) $args['rows'];
  23.     $category = $args['category'];
  24.     $tag = $args['tag'];
  25.     $orderby = $args['orderby'];
  26.     $order = $args['order'];
  27.     // get the products
  28.     $args = array(
  29.       'posts_per_page'  => $rows,
  30.       'offset'          => 0,
  31.       'post_status'     => 'publish',
  32.       'post_type'       => 'product',
  33.       'product_cat'     => $category,
  34.       'product_tag'     => $tag,
  35.       'orderby'         => $orderby,
  36.     'order'         => $order,
  37.     );
  38.     $posts_list = get_posts( $args );
  39.     if ( count( $posts_list ) ) {
  40.       $html = '<table class="products-list">'.PHP_EOL;
  41.       $html .= '<tbody>';
  42.       foreach ( $posts_list as $post ) {
  43.         setup_postdata( $post );
  44.         $html .= '<tr>'.PHP_EOL;
  45.         $my_title = get_the_title();
  46.         $my_permalink = get_the_permalink();
  47.         $html .= '<td><a href="'.$my_permalink.'">'.$my_title.'</a></td>'.PHP_EOL;
  48.         $_product = wc_get_product( $post->ID );
  49.         $data = $_product->get_availability(); // gives an array
  50.         $html .= '<td><span class='.$data['class'].'>'.$data['availability']. '</span></td>'.PHP_EOL;
  51.         $price = $_product->get_price_html();
  52.         $html .= '<td class="products-list-price">'.$price.'</td>'.PHP_EOL;
  53.         $html .= '</tr>'.PHP_EOL;
  54.         wp_reset_postdata();
  55.       }
  56.       $html .= '</tbody>';
  57.       $html .= '</table>'.PHP_EOL;
  58.     } else {
  59.       $html = 'No products found'.PHP_EOL;
  60.     }
  61.     return $html;
  62.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement