Daniel B
Daniel B

Reputation: 74

How to display the term name used in a custom loop using a tax_query in wordpress

I want to display the 'term name' dynamically based on the term slug used in tax_query.

I need the value Novedades which is the name of the term that has the slug 'novedades', that I use in 'terms' => 'novedades'.

It should be displayed in the h2 tag. How can I grab that value?

My code:

<?php
    $args = array(
        'post_type' => 'cuadros',
        'post_per_page' => 4,
        'tax_query' => array(
            array(
                'taxonomy' => 'tipo_de_cuadro',
                'field' => 'slug',
                'terms' => 'novedades'
            ),
        ),
    );
    
    $postQuery = new WP_Query($args);
?>

<?php if ( $postQuery->have_posts()) : ?>

<div class="product-carousel">

     <h2> x x x x x x x x x x x x x x </h2>

     <div class="owl-carousel">

     <?php while( $postQuery->have_posts() ) : $postQuery->the_post(); ?>

         <div class="product-carousel__item">
             <img src="<?php the_post_thumbnail_url(); ?>" alt="">
             <h3><?php the_title(); ?></h3>
             <p class="producr-carousel__precio">desde $595</p>
             <a href="<?php the_permalink(); ?>" class="producr-carousel__button">Detalles</a>
         </div>
        
     <?php endwhile; wp_reset_postdata(); ?>

    </div>
</div>

<?php endif; ?>

Upvotes: 1

Views: 1538

Answers (1)

FluffyKitten
FluffyKitten

Reputation: 14312

There are a few ways to do this, but given that you know what the slug is then the easiest way is probably to use the get_term_by function.

You can use the slug to get all the term details using get_term_by including the name. This is separate to your WP_Query , so you can use it outside the loop.

<?php
// set up variables for the slug & taxonomy - then this can all be changed dynamically if you need to
$term_slug = "novedades";
$term_taxonomy = "tipo_de_cuadro";

// Pass the slug & taxonomy to get_term_by to get all the term details
$term = get_term_by('slug', $term_slug, $term_taxonomy); 
$term_name = $term->name;    // get the name from the term

$args = array(
    'post_type' => 'cuadros',
    'post_per_page' => 4,
    'tax_query' => array(
        array(
            'taxonomy' => $term_taxonomy,
            'field' => 'slug',
            'terms' => $term_slug
        ),
    ),
);

$postQuery = new WP_Query($args);
if ( $postQuery->have_posts()) : ?>

    <div class="product-carousel">

        <!-- you can use your term_name variable here  before you set the_post -->
        <h2><?php echo $term_name; ?></h2>
        <!-- [do stuff....] -->
    </div>
<?php endif; ?>

Upvotes: 1

Related Questions