在文章中加入微数据ImageObject

富媒体搜索结果支持的微数据,在WordPress文章中怎么写?首先在the loop循环中插入:

// inLanguage
preg_match( '/lang="(.*?)"/', get_language_attributes(), $match );
$lang = $match[1];
echo '<meta itemprop="inLanguage" content="' . $lang . '" />';

// image
$post_content = get_the_content();
preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i', $post_content, $images );
if ( !empty( $images ) ) {
  foreach ( $images[1] as $image ) {
    $img_data = getimagesize( $image );
    echo '<div class="d-none" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
            <meta itemprop="url" content="' . $image . '">
            <meta itemprop="width" content="' . $img_data[0]  . '">
            <meta itemprop="height" content="' . $img_data[1]  . '">
          </div>';
  }
}

记得要在WordPress主题代码中插入。

如果觉得麻烦,不想修改主题,则可以通过自定义代码的方式,使用以下代码即可:

function add_itemprop_to_images( $content ) {
  return preg_replace( '/<img (.*?)\/>/', '<img itemprop="image" $1 />', $content );
}
add_filter( 'the_content', 'add_itemprop_to_images' );

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

发表回复

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