• I need to display results that meet two criteria: both the value in the custom field and the category must match. For example, I would like to display all results whose category is ‘Clothing’, and whose custom field meta_easyfatt_libero_1 contains the value ‘MEN’. Here is the code I currently use for custom fields, but I can’t figure out how to modify it to fit my requirement.

        <?php
    /* Template Name: Template Uomo */

    get_header(); ?>

    <div class="easyfatt-products-list">
    <h1><center>Prodotti UOMO</center></h1>
    <?php
    // Imposta il numero di prodotti per pagina e la query
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args = array(
    'post_type' => 'product',
    'posts_per_page' => 15, // Mostra 12 prodotti per pagina
    'paged' => $paged,
    'meta_query' => array(
    array(
    'key' => 'meta_easyfatt_libero_1',
    'value' => 'UOMO',
    'compare' => 'LIKE',
    ),
    ),
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) { ?>
    <div class="products-grid">
    <?php while ($query->have_posts()) {
    $query->the_post(); ?>
    <div class="product">
    <?php if (has_post_thumbnail()) {
    the_post_thumbnail('medium'); // Mostra l'immagine del prodotto
    } else {
    echo '<img src="' . wc_placeholder_img_src() . '" alt="Placeholder Image">';
    } ?>
    <h2><?php the_title(); ?></h2>
    <a href="<?php the_permalink(); ?>">Visualizza</a>
    </div>
    <?php } ?>
    </div>

    <!-- Paginazione -->
    <div class="pagination">
    <?php
    echo paginate_links(array(
    'total' => $query->max_num_pages,
    'current' => $paged,
    ));
    ?>
    </div>
    <?php
    } else {
    echo '<p>Nessun prodotto trovato in questa categoria.</p>';
    }

    wp_reset_postdata();
    ?>
    </div>

    <?php get_footer(); ?>
Viewing 1 replies (of 1 total)
  • To display products that meet both a specific category and a custom field value, you can modify your query as follows:

    $args = array(
    'post_type' => 'product',
    'posts_per_page' => 15,
    'paged' => $paged,
    'tax_query' => array(
    array(
    'taxonomy' => 'product_cat',
    'field' => 'slug',
    'terms' => 'clothing',
    ),
    ),
    'meta_query' => array(
    array(
    'key' => 'meta_easyfatt_libero_1',
    'value' => 'MEN',
    'compare' => 'LIKE',
    ),
    ),
    );

    The tax_query section is responsible for including only those products in the ‘Clothing’ category. Meanwhile, the meta_query checks that the custom field meta_easyfatt_libero_1 contains the value ‘MEN’. By combining these two elements, your query will effectively display only the products that meet both criteria. For more details on WP_Query check out this https://developer.www.ads-software.com/reference/classes/wp_query/

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.