Página front Page
- <h3>Filtro de productos</h3>
- <select name="categorias-productos">
- <option value="">Todas las categorías</option><!--?php $terms = get_terms('product_cat', array('hide_empty' => true));<br ?--> foreach($terms as $term){
- </select>
- <select name="categorias-productos">echo '
- <option value="'. $term->slug . '">'. $term->name. '</option>';
- </select>
- <select name="categorias-productos">}
- </select>
- <select name="categorias-productos">?>
- </select>
- <div id="resultado-productos"></div>
Dentro de functions.php
- 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' => admin_url('admin-ajax.php') )); } add_action("wp_ajax_nopriv_wdmFiltroProductos", "wdmFiltroProductos"); add_action("wp_ajax_wdmFiltroProductos", "wdmFiltroProductos"); function wdmFiltroProductos(){ $args = array( 'post_type' =>'product', 'posts_per_page' => -1, 'order' => 'ASC', 'order_by' =>'title' ); if($_POST['product_cat']){ $args['tax_query'] = array( array( 'taxonomy' =>'product_cat', 'field' =>'slug', 'terms' => $_POST['product_cat'] ) ); } $productos = new WP_Query($args); if($productos->have_posts()){ $return = array(); while($productos->have_posts()){ $productos->the_post(); $return[] = array( 'imagen' => get_the_post_thumbnail(get_the_id(),'large'), 'link' => get_the_permalink(), 'title' => get_the_title() ); } wp_send_json($return); } }
Archivo custom.js
- (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 => { html += `
- <ul>
- <li style="width: 30%; display: inline-block; margin-right: 10px;">
- <figure>${item.imagen}</figure>
- <h4><a href="${item.link}">${item.title}</a></h4>
- </li>
- </ul>
- ` }) $("#resultado-productos").html(html); }, error: function(error){ console.log(error) } }); }); })(jQuery);