【问题标题】:Print icon for taxonomy terms分类术语的打印图标
【发布时间】:2018-03-14 13:25:59
【问题描述】:

在我的 wordpress 主题中 Taxonomy = my-category 和类别是 AB,AC,AD 等自定义帖子类型。

我想打印自定义类别的图标,并在index.php 上使用wp_query 内的if & else 语句,下面是我的代码。

 $args = array(
 'post_type'      => 'mycpt',
 'posts_per_page' => 10,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
  while( $query->have_posts() ) {
    $query->the_post(); 
    the_content();

if ($term_id === 10){
    echo '<p class="icon-gear"></p>';
}
else if ($term_id === 11){
    echo '<p class="icon-star"></p>';
}
else if ($term_id === 12){
    echo '<p class="icon-tv"></p>';
}   
 //and continuous  ..............
}
}

CSS

 .icon-gear:before { background:url('gear.svg') no-repeat; }
 .icon-star:before { background:url('star.svg') no-repeat; }
 .icon-tv:before { background:url('tv.svg') no-repeat; }

如何打印分类类别的 svg 图标?

【问题讨论】:

  • 如果您打算使用类似的 if else,请改用 switch。你也可以通过说switch ($term_id) case 10: $icon = "star"; 然后echo "&lt;p class='icon-$icon'"; 来避免重复代码你能告诉你出了什么问题吗?因为你说的是​​你想要发生的事情,而不是现在发生的事情。
  • 你从哪里得到$term_id
  • @ikdekker 它没有显示任何东西。没有错误的空框
  • 如果您通过查看页面源来检查 html,是否出现了

    元素?如果是这样,您可以尝试从 css 中删除 :before。

  • @ikdekker 在页面源中为空。 &lt;p&gt; 不显示

标签: php wordpress taxonomy


【解决方案1】:

测试代码,试试这个

 $args = array(
 'post_type'      => 'mycpt',
 'posts_per_page' => 10,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
  while( $query->have_posts() ) {
    $query->the_post(); 
    the_content();

$terms = get_the_terms( $post->ID, 'my-category');
foreach ( $terms as $term ) {
    $termID[] = $term->term_id;
}
if ($termID[0] === 10){
    echo '<p class="icon-gear"></p>';
}
else if ($termID[0] === 11){
    echo '<p class="icon-star"></p>';
}
else if ($termID[0] === 12){
    echo '<p class="icon-tv"></p>';
}   
 //and continuous  ..............
}
}

【讨论】:

    【解决方案2】:

    我认为这是错误的做法,并且不可维护。

    就个人而言,我会考虑使用自定义字段将文本字段添加到您的类别中,您可以通过仪表板为每个类别设置图标。然后,您只需在循环期间回显一个自定义字段,如果它为空,则可以默认为空白/默认图标。

    如果您还没有使用高级自定义字段插件,请查看它。

    【讨论】:

    • 我想如果没有插件可以实现。有可能吗?
    • 是的,使用 ACF 会容易得多,但如果您不想使用插件,请查看本指南:pippinsplugins.com/adding-custom-meta-fields-to-taxonomies
    • 问题是每个插件包括 ACF 只在taxonomy.phpcategory.php 上显示图像而不是在索引上。我已经提到有问题需要在 index.php 上打印
    • ACF 也应该能够在索引上执行此操作 - 当您查询索引时,它也会显示为 cat 和 tax
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多