Página front Page

  1. <h3>Filtro de productos</h3>
  2. <select name="categorias-productos">
  3. <option value="">Todas las categorías</option><!--?php $terms = get_terms('product_cat', array('hide_empty' => true));<br ?--> foreach($terms as $term){
  4. </select>
  5. <select name="categorias-productos">echo '
  6. <option value="'. $term-&gt;slug . '">'. $term-&gt;name. '</option>';
  7. </select>
  8. <select name="categorias-productos">}
  9. </select>
  10. <select name="categorias-productos">?&gt;
  11. </select>
  12. <div id="resultado-productos"></div>

Dentro de functions.php

  1. add_action('wp_enqueue_scripts','template_styles'); function template_styles(){ wp_enqueue_script('custom',get_template_directory_uri() .'/js/custom.js', false,'1.1', true); wp_localize_script('custom', 'wdm',array( 'ajaxurl' =&gt; admin_url('admin-ajax.php') )); } add_action("wp_ajax_nopriv_wdmFiltroProductos", "wdmFiltroProductos"); add_action("wp_ajax_wdmFiltroProductos", "wdmFiltroProductos"); function wdmFiltroProductos(){ $args = array( 'post_type' =&gt;'product', 'posts_per_page' =&gt; -1, 'order' =&gt; 'ASC', 'order_by' =&gt;'title' ); if($_POST['product_cat']){ $args['tax_query'] = array( array( 'taxonomy' =&gt;'product_cat', 'field' =&gt;'slug', 'terms' =&gt; $_POST['product_cat'] ) ); } $productos = new WP_Query($args); if($productos-&gt;have_posts()){ $return = array(); while($productos-&gt;have_posts()){ $productos-&gt;the_post(); $return[] = array( 'imagen' =&gt; get_the_post_thumbnail(get_the_id(),'large'), 'link' =&gt; get_the_permalink(), 'title' =&gt; get_the_title() ); } wp_send_json($return); } }

Archivo custom.js

javascript

  1. (function($){ $("#categorias-productos").change(function(){ $.ajax({ url: wdm.ajaxurl, method:"POST", data: { "action": "wdmFiltroProductos" , "product_cat": $(this).find(':selected').val() }, beforeSend: function(){ $("#resultado-productos").html("Cargando...") }, success: function(data){ // console.log(data) let html = ""; data.forEach(item =&gt; { html += `
  2. <ul>
  3.     <li style="width: 30%; display: inline-block; margin-right: 10px;">
  4. <figure>${item.imagen}</figure>
  5. <h4><a href="${item.link}">${item.title}</a></h4>
  6. </li>
  7. </ul>
  8. ` }) $("#resultado-productos").html(html); }, error: function(error){ console.log(error) } }); }); })(jQuery);
Comparte conocimiento en tus redes sociales...Share on Facebook
Facebook
Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin
Email this to someone
email
Pin on Pinterest
Pinterest
Share on Tumblr
Tumblr
Print this page
Print