wordpress - 如何在 wordpress 中使用 tax_query 显示自定义循环中使用的术语名称
问题描述
我想根据 tax_query 中使用的术语 slug 动态显示“术语名称”。
我需要值 Novedades,它是具有 slug 'novedades' 的术语的名称,我在'terms' => 'novedades'
.
它应该显示在 h2 标签中。我怎样才能抓住这个价值?
我的代码:
<?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; ?>
解决方案
有几种方法可以做到这一点,但鉴于您知道 slug 是什么,那么最简单的方法可能是使用get_term_by
function。
您可以使用 slug 获取所有术语详细信息,get_term_by
包括名称。这与您的 WP_Query 是分开的,因此您可以在循环之外使用它。
<?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; ?>
推荐阅读
- javascript - 带有mongoDB的后端节点js,补丁请求不更新日期类型值
- entity-framework - EF Core 有查询队列吗?
- reactjs - 如何使用 CDN 将 React 组件作为 npm 包提供服务
- python - 相对于指标连接列中的单元格
- google-visualization - 如何添加垂直线和注释谷歌时间线图
- angular - 如何使用 Angular 11 实现加密图表小部件
- reactjs - styled() 中 shouldForwardProp 选项的目的是什么?
- php - 我是否可以使用从我的 laravel 控制器中的 ajax GET REQUEST 获取的数据更新数据库,而无需进一步的 ajax 请求成功?
- java - 如何在 Java 中验证用户输入
- typescript - 是否可以使用该类的实例获取该类的静态方法的类型?