Wordpress 使用 get_term 检索未按预期工作的 slug [英] Wordpress using get_term to retrieve slug not working as expected

查看:18
本文介绍了Wordpress 使用 get_term 检索未按预期工作的 slug的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码尝试获取当前类别和父类别的 slug.

I'm using the below code to try and get the slug for the current category and the parent category.

我已经设法获得了当前的 cat slug,但父级以可读文本和 nut slug 格式显示.

I've managed to get as far as getting the currently cat slug but the parent displays in readable text and nut slug format.

我哪里出错了?

    <?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
    $parent = get_term($term->parent, get_query_var('taxonomy') );?>

        <?php echo do_shortcode("[ecs-list-events cat='{$term->slug}']"); ?>   

     <?php 
    echo $term->slug; 
    echo $parent->name;
    ?>

推荐答案

我最近刚刚自己设置了这样的东西.这是我用来完成类似操作的代码:

I just recently setup something like this myself. Here is the code I used to accomplish something similar:

<?php 
    global $post;    
    $terms = get_the_terms($post->id, 'my-custom-taxonomy-name');   
    $term = get_term_by( 'id', $terms[0]->term_id, 'my-custom-taxonomy-name');
    $parent = get_term($term->parent, 'my-custom-taxonomy-name' );

    echo $parent->slug; //This will return the parent slug
?>

使用您的代码,您可以像这样完成:

Using your code, you can accomplish this like so:

<?php 
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
$parent = get_term($term->parent, get_query_var('taxonomy') );
?>

<?php echo do_shortcode("[ecs-list-events cat='{$term->slug}']"); ?>   

<?php 
echo $term->slug; 
echo $parent->slug; //change this to "slug"
?>

您可能只需要更改echo $parent->name;"到echo $parent->slug;".此外,您应该查看这些文章以了解可以从 get_term_by()get_term() 函数.

You might just need to change "echo $parent->name;" to "echo $parent->slug;". In addition, you should review these articles to see what parameters can be returned from the get_term_by() and get_term() functions.

如果这有帮助,请告诉我.

Please let me know if this helps.

这篇关于Wordpress 使用 get_term 检索未按预期工作的 slug的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆