I tried to get array of featured products to use theme in my own plugin with jquery slider I have made this function and get attrs from class-wc-shortcodes.php but no results
add_shortcode('soqopslider', 'wps_soqopslider'); function wps_soqopslider() { $atts = shortcode_atts( array( 'per_page' => '12', 'columns' => '4', 'orderby' => 'date', 'order' => 'desc', 'category' => '', // Slugs 'operator' => 'IN', // Possible values are 'IN', 'NOT IN', 'AND'. ), $atts, 'featured_products' ); $meta_query = WC()->query->get_meta_query(); $tax_query = WC()->query->get_tax_query(); $tax_query[] = array( 'taxonomy' => 'product_visibility', 'field' => 'name', 'terms' => 'featured', 'operator' => 'IN', ); $query_args = array( 'post_type' => 'product', 'post_status' => 'publish', 'ignore_sticky_posts' => 1, 'posts_per_page' => $atts['per_page'], 'orderby' => $atts['orderby'], 'order' => $atts['order'], 'meta_query' => $meta_query, 'tax_query' => $tax_query, ); // The Query $the_query = new WP_Query( query_args ); // The Loop if ( $the_query->have_posts() ) { echo '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li>' . get_the_title() . '</li>'; } echo '</ul>'; /* Restore original Post Data */ wp_reset_postdata(); } else { echo "No featured products found :("; } return "<span style='background:green;color:white;' >nothing</span>"; }
what I must add or change to get it works I use it now as shortcode in welcome page just for testing
Advertisement
Answer
There was some errors in your code. So I have made the necessary changes.
Also the Shortcode data has to be returned not echoed.
Here is the functional code:
add_shortcode('soqopslider', 'wps_soqopslider'); function wps_soqopslider( $atts) { $atts = shortcode_atts( array( 'per_page' => '12', 'columns' => '4', 'orderby' => 'date', 'order' => 'desc', 'category' => '', // Slugs 'operator' => 'IN', // Possible values are 'IN', 'NOT IN', 'AND'. ), $atts, 'soqopslider' ); $meta_query = WC()->query->get_meta_query(); $tax_query = WC()->query->get_tax_query(); $tax_query[] = array( 'taxonomy' => 'product_visibility', 'field' => 'name', 'terms' => 'featured', 'operator' => 'IN', ); $query_args = array( 'post_type' => 'product', 'post_status' => 'publish', 'ignore_sticky_posts' => 1, 'posts_per_page' => $atts['per_page'], 'orderby' => $atts['orderby'], 'order' => $atts['order'], 'meta_query' => $meta_query, 'tax_query' => $tax_query, ); // The Query $the_query = new WP_Query( $query_args ); $html = '</ul>'; // The Loop if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); $html .= '<li>' . get_the_title() . '</li>'; } // Restore original Post Data wp_reset_postdata(); // Output return $html . '</ul>'; } else { return "No featured products found :("; } } ## BASIC USAGE: [soqopslider] # ---- #
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and will output a list of feature products titles.