Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Shortcode to make a list of products from a category
- // usage: [products_list rows="-1" category="kits" orderby="title" order="ASC"]
- // rows defaults to -1, show all products
- // category defaults to '', empty: shows all categories, value: category slug
- // orderby defaults to 'title'
- // order defaults to 'DESC'
- // for orderby options see: https://codex.wordpress.org/Template_Tags/get_posts
- // code goes in functions.php for your child theme
- add_shortcode('products_list', 'products_list');
- function products_list( $atts ) {
- global $post;
- // get the parameters
- $args = shortcode_atts( array(
- 'rows' => -1,
- 'category' => '',
- 'tag' => '',
- 'orderby' => 'title',
- 'order' => 'ASC'
- ), $atts );
- $rows = (int) $args['rows'];
- $category = $args['category'];
- $tag = $args['tag'];
- $orderby = $args['orderby'];
- $order = $args['order'];
- // get the products
- $args = array(
- 'posts_per_page' => $rows,
- 'offset' => 0,
- 'post_status' => 'publish',
- 'post_type' => 'product',
- 'product_cat' => $category,
- 'product_tag' => $tag,
- 'orderby' => $orderby,
- 'order' => $order
- );
- $posts_list = get_posts( $args );
- if ( count( $posts_list ) ) {
- $html = '<table class="products-list">'.PHP_EOL;
- $html .= '<tbody>';
- foreach ( $posts_list as $post ) {
- setup_postdata( $post );
- $html .= '<tr>'.PHP_EOL;
- $img_html = woocommerce_get_product_thumbnail( 'shop_thumbnail' );
- $html.= '<td>'.$img_html.'</td>'.PHP_EOL;
- $my_title = get_the_title();
- $html .= '<td>'.$my_title.'</td>'.PHP_EOL;
- $_product = wc_get_product( $post->ID );
- $price = $_product->get_price_html();
- $html .= '<td>'.$price.'</td>'.PHP_EOL;
- $my_permalink = get_the_permalink();
- $html .= '<td><a href="'.$my_permalink.'" target="_blank" class="button">Details</a></td>'.PHP_EOL;
- $html .= '</tr>'.PHP_EOL;
- wp_reset_postdata();
- }
- $html .= '</tbody>';
- $html .= '</table>'.PHP_EOL;
- } else {
- $html = 'No products found'.PHP_EOL;
- }
- return $html;
- }
- ?>
- /* custom styles for the product_list */
- /* may need modifying to suit your theme */
- /* Custom css can be entered at: Dashboard > Appearance > Customise > Additional CSS */
- /* do not put in functions.php */
- .entry-content .products-list tr {
- border-style:solid;
- border-color:#ddd;
- border-width:1px 0
- }
- .entry-content .products-list td {
- padding:0 16px;
- border:none
- }
- .entry-content .products-list td img {
- width:40px;
- height:40px;
- }
- .products-list .button {
- padding:4px 16px;
- border:1px solid #bbb;
- border-radius:6px;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement