Carbon Fields中做一个JSON LD问答类型

富媒体搜索结果对SEO至关重要,之前谈到Carbon Fields框架,今天做一个问答类型的JSON LD。

你可以在functions.php中使用Carbon Fields的API定义一个带有两个字段(qus和ans)的complex类型。然后,你可以创建一个模板文件,并在该文件中使用Carbon Fields的API将complex类型的内容输出为JSON LD问答类型。代码如下:

// 在functions.php中定义complex类型
use Carbon_Fields\Container;
use Carbon_Fields\Field;

add_action( 'carbon_fields_register_fields', 'crb_attach_complex_field' );
function crb_attach_complex_field() {
    Container::make( 'post_meta', '问答' )
        ->add_fields( array(
            Field::make( 'complex', 'qa_list', '问题列表' )
                ->add_fields( array(
                    Field::make( 'text', 'qus', '问题' ),
                    Field::make( 'text', 'ans', '答案' ),
                ) ),
        ) );
}

// 在模板文件中输出complex类型的内容
$qa_list = carbon_get_post_meta( get_the_ID(), 'qa_list' );
$qa_list = array_map( function( $qa ) {
    return array(
        "@type" => "Question",
        "name" => $qa['qus'],
        "acceptedAnswer" => array(
            "@type" => "Answer",
            "text" => $qa['ans'],
        ),
    );
}, $qa_list );

echo '<script type="application/ld+json">';
echo json_encode( array(
    "@context" => "https://schema.org",
    "@type" => "FAQPage",
    "mainEntity" => $qa_list,
) );
echo '</script>';

这段代码将complex类型的内容输出为JSON LD问答类型,并可以在页面上显示。

分类 WordPress技巧 本文由 清白之年 原创发布,转载请注明文章来源。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注