AMPのフィルターを使ったカスタマイズ

[amp_sidebar]

この記事は、プラグインのreadme.mdで紹介されているAMPフィルターの動作テストを行ったメモです。

AMPプラグイン

amp-featured

AMPにアイキャッチ画像を追加

/**
 * 
 */
add_action( 'pre_amp_render_post', 'xyz_amp_add_custom_actions' );
function xyz_amp_add_custom_actions() {
	add_filter( 'the_content', 'xyz_amp_add_featured_image' );
}

function xyz_amp_add_featured_image( $content ) {
	if ( has_post_thumbnail() ) {
		// Just add the raw <img /> tag; our sanitizer will take care of it later.
		$image= sprintf( '<p class="xyz-featured-image">%s</p>', get_the_post_thumbnail() );
		$content= $image . $content;
	}
	return $content;
}

ページ幅の変更

amp-content-width

add_filter( 'amp_content_max_width', 'xyz_amp_change_content_width' );

function xyz_amp_change_content_width( $content_max_width ) {
	return 1200;
}

AMPプラグインのテンプレートではなく、テーマ内のテンプレートを使用する

add_filter( 'amp_post_template_file', 'xyz_amp_set_custom_tax_meta_template', 10, 3 );

function xyz_amp_set_custom_tax_meta_template( $file, $type, $post ) {
	if ( basename( $file )=== 'single.php' ) {
		$file= get_stylesheet_directory().'/amp-single.php';
	}
	return $file;
}

著者の表示を削除

amp-remove-author

add_filter( 'amp_post_template_meta_parts', 'xyz_amp_remove_author_meta' );

function xyz_amp_remove_author_meta( $meta_parts ) {
	foreach ( array_keys( $meta_parts, 'meta-author', true ) as $key ) {
		unset( $meta_parts[ $key ] );
	}
	return $meta_parts;
}

カテゴリーリストや著者情報のメタブロックにコンテンツを差し込む

amp-custom-item

add_filter( 'amp_post_template_meta_parts', 'xyz_amp_add_item' );

function xyz_amp_add_block( $meta_parts ) {
	$meta_parts[]= 'xyz_amp_add_item';
	return $meta_parts;
}

add_filter( 'amp_post_template_file', 'xyz_amp_add_item_path', 10, 3 );

function xyz_amp_add_item_path( $file, $type, $post ) {
	if ( 'xyz_amp_add_item'=== $type ) {
		$file= get_stylesheet_directory().'/amp-hoge.php';
	}
	return $file;
}

CSSの追加

add_action( 'amp_post_template_css', 'xyz_amp_my_additional_css_styles' );

function xyz_amp_my_additional_css_styles( $amp_template ) {
	// only CSS here please...
	?>
	.amp-wp-byline amp-img {
		border-radius: 0; /* we don't want round avatars! */
	}
	.my-custom-class {
		color: blue;
	}
	<?php
}

クエリ―文字列を変更する

add_filter( 'amp_query_var' , 'xyz_amp_change_endpoint' );

function xyz_amp_change_endpoint( $amp_endpoint ) {
	return 'foo';
}

フッターにクレジットなどを追加する

add_action( 'amp_post_template_footer', 'amp_custom_footer' );

function amp_custom_footer(){
	
	echo '<address>http://example.com</address>';
}

AMPパーマリンクの取得

amp_get_permalink($post_id);

AMPページかどうかの条件分岐

is_amp_endpoint()

関連

組み込みコンポーネント – AMP について

[emulsion_relate_posts]