【问题标题】:Get parent of custom taxonomy in Yoast variable snippet在 Yoast 变量片段中获取自定义分类法的父级
【发布时间】:2020-05-03 03:44:58
【问题描述】:

我有一个使用自定义分类法的目录 wordpress 网站。层次结构设置如下:国家>州>城市。当我将自定义分类法放入 Yoast 以获取 SEO 标题和元描述时,它只在城市中拉动。我还希望通过创建一个新的 Yoast 变量 sn-p 来获取状态,该变量将获取用户所在的当前 URL 的父级(即状态)。

这是我的functions.php 文件中目前为止的内容,但它正在引入国内。因此,它目前正在引入顶级父级。我怎样才能得到直系父母,这将是状态?

function get_state() {
$myterms = get_terms( array( 'taxonomy' => 'w2dc-location', 'parent' => 0 ) );
  foreach($myterms as $term) {
    return $term->name;
  }
}

function register_custom_yoast_variables() {
   wpseo_register_var_replacement( '%%state%%', 'get_state', 'advanced', 'some help text' );
}

add_action('wpseo_register_extra_replacements', 'register_custom_yoast_variables');

网站链接:https://www.helpingmehear.com/find-an-expert/hearing-aids/united-states/colorado/castle-rock/accent-on-hearing/

【问题讨论】:

    标签: wordpress function parent-child taxonomy yoast


    【解决方案1】:

    这是一个返回城市和州的解决方案,因为您只选择了一个分类(城市)并且该州是城市的直接父级。我认为你想使用get_the_terms()而不是get_terms()

    function get_state() {
        global $post;
        // Get the terms for the current post in your tax
        $myterms = get_the_terms( $post->ID, 'w2dc-location' );
        // Check if parent exists
        if ($myterms[0]->parent !== 0){
            // Get the term object
            $parent = get_term_by('id', $myterms[0]->parent, 'w2dc-location');
            return $parent->name;
        }
    }
    
    function register_custom_yoast_variables() {
       wpseo_register_var_replacement( 'state', 'get_state', 'advanced', 'some help text' );
    }
    add_action('wpseo_register_extra_replacements', 'register_custom_yoast_variables');
    

    在 Yoast 标题框中的用法...

    %%category%% %%state%%

    【讨论】:

    • 工作完美。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    相关资源
    最近更新 更多