0

下面的代码用于通过查询字符串更改标题和元描述。只有一页有 3 个查询字符串。其他页面没有查询字符串。使用functions.php 中的代码,Yoast 标题和元描述的其他页面无法正常工作。没有代码,Yoast 标题和元描述可以正常工作。有没有办法让代码在仍然使用 Yoast 标题和元描述的同时工作?

/* Changing title and meta description by query strings */
function yoast_add_title (){
    if ( ! empty( $_GET[ 'q' ] ) && $_GET['q'] == 'medical' ) {
        $title = 'Health';
    }
    if ( ! empty( $_GET[ 'q' ] ) && $_GET['q'] == 'wealth' ) {
        $title = 'Financial';
    }
    if ( ! empty( $_GET[ 'q' ] ) && $_GET['q'] == "retirement" ) {
        $title = 'Wealth';
    }
    return $title; 
}

function yoast_add_metadesc (){
    if ( ! empty( $_GET[ 'q' ] ) && $_GET['q'] == 'medical' ) {
        $metadesc = 'Health';
    }
    if ( ! empty( $_GET[ 'q' ] ) && $_GET['q'] == 'wealth' ) {
        $metadesc = 'Financial';
    }
    if ( ! empty( $_GET[ 'q' ] ) && $_GET['q'] == "retirement" ) {
        $metadesc = 'Wealth';
    }
    return $metadesc; 
}

add_filter( 'wpseo_title', 'yoast_add_title', 10, 1);
add_filter( 'wpseo_metadesc', 'yoast_add_metadesc', 10, 1);
4

1 回答 1

0

下面的代码可以在 functions.php 中使用。不知何故,我需要定位确切的页面 id 并使用 template_redirect。

function yoast_add_title (){
    if ( $_GET['q'] == 'medical' ) {
        $title = 'Health';
    }
    if ( $_GET['q'] == 'wealth' ) {
        $title = 'Financial';
    }
    if ( $_GET['q'] == 'retirement' ) {
        $title = 'Wealth';
    }
    return $title;
}

function yoast_add_metadesc (){
    if ( $_GET['q'] == 'medical' ) {
        $metadesc = 'Health';
    }
    if ( $_GET['q'] == 'wealth' ) {
        $metadesc = 'Financial';
    }
    if ( $_GET['q'] == 'retirement' ) {
        $metadesc = 'Wealth';
    }
    return $metadesc; 
}

function yoast_add_all (){
    if ( is_page(50) && ( ! empty( $_GET[ 'q' ] ) ) ) { 
        add_filter( 'wpseo_title', 'yoast_add_title', 10, 1 );
        add_filter( 'wpseo_metadesc', 'yoast_add_metadesc', 10, 1 );
    }
}

add_action( 'template_redirect', "yoast_add_all" );
于 2018-04-26T00:16:21.400 回答