个性化阅读
专注于IT技术分析

在WordPress中使用get_option()定义自定义字段

点击下载

我有一些自定义设置页面来定义一些全局变量。因此, 现在我可以使用以下命令打印变量:

echo get_option('dealcity');

但是我需要能够在Yoast的页面标题中使用结果, 但是使用Yoasts自定义字段代码%% cf_dealcity %%无效。我猜是因为Dealcity是一个选项设置, 而不是自定义字段。所以我认为我需要将选项定义为自定义字段。我尝试使用以下命令, 然后尝试%% cf_dealercity %%, 但这没有用:

function save_your_fields_meta( $post_id ) {   
$dealercity = get_option('dealcity');
}
add_action( 'save_post', 'save_your_fields_meta' );

#1


根据你的代码片段, 你可能只是在寻找更新save_post挂钩上的自定义字段?在你的示例中, 什么都不会发生, 因为在定义$ dealcity之后你不对其执行任何操作, 并且需要使用update_post_meta()保存它:

function chrislovessushi_fields_meta( $post_id ){   
    if( $dealcity = get_option( 'dealcity' ) ){
        // Make sure $dealcity exists, then update the post meta
        update_post_meta( $post_id, 'dealcity', $dealcity );
    }
}
add_action( 'save_post', 'chrislovessushi_fields_meta' );

同样, 对于将来的大脑糖果, 你可以使用一些简单的过滤器来修改页面标题, 例如, 用于页面标题的the_title和/或用于<title>标签的wp_title:

function chrislovessushi_title_filter( $title, $id = null ) {
    if( is_page() ){
        // Add `dealcity` value before title if this is a page
        $title = get_option('dealcity').' '.$title;
    }
    return $title;
}
add_filter( 'the_title', 'chrislovessushi_title_filter', 10, 2 );
赞(0)
未经允许不得转载:srcmini » 在WordPress中使用get_option()定义自定义字段

评论 抢沙发

评论前必须登录!