Página front Page

  1. <h3>Filtro de productos</h3>
  2. <select name="categorias-productos"><option value="">Todas las categorías</option>
  3. $terms = get_terms('product_cat', array('hide_empty' => true));
  4. foreach($terms as $term){
  5. echo '<option value="'. $term->slug . '">'. $term->name. '</option>';
  6. }
  7. </select>
  8. <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

  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
Share on google
Google
Share on twitter
Twitter
Share on linkedin
Linkedin
Share on email
Email
Share on pinterest
Pinterest
Share on tumblr
Tumblr
Share on print
Print