因為我的文章幾乎沒有設定特色圖片, 所以AMP當然找不到 image, 一樣的邏輯要去設定讓系統可以抓到第一張圖片, 使用到的語法可以參考這一篇文章: wordpress 快速設定 文章的第一張圖片為縮圖
但是, 當然還是要整合一下, 必須看你使用的外掛或程式碼是如何去撈 image url的
以我自己為例, 使用Google推薦外掛AMP for WP – Accelerated Mobile Pages for WordPress
修改accelerated-mobile-pages/templates/features.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
/* 我的修改開始 */ add_action( 'get_feature_image', 'get_feature_image' ); function get_feature_image($post_id = null){ //傳入post_id 參數去指定何篇文章 global $post, $posts; $first_img = ''; if($post_id) $post = get_post( $post_id ); //可以傳post_id去指定何篇文章 if ( has_post_thumbnail() ) { $first_img = wp_get_attachment_url( get_post_thumbnail_id() ); } else { ob_start(); ob_end_clean(); $output = preg_match('/<*img[^>]*src*=*["\']?([^"\']*)/i', $post->post_content, $matches); $first_img = $matches[1]; } return $first_img; } /* 我的修改結尾 */ // 13. Add Custom Placeholder Image for Structured Data. // if there is no image in the post, then use this image to validate Structured Data. add_filter( 'amp_post_template_metadata', 'ampforwp_update_metadata_featured_image', 10, 2 ); function ampforwp_update_metadata_featured_image( $metadata, $post ) { global $redux_builder_amp; global $post; $post_id = get_the_ID() ; $post_image_id = get_post_thumbnail_id( $post_id ); $structured_data_image = wp_get_attachment_image_src( $post_image_id, 'full' ); $post_image_check = $structured_data_image; /* 我的修改開始 */ //$structured_data_image_url = ''; $structured_data_image_url = get_feature_image( $post_id ); /* 我的修改結尾 */ if ( $post_image_check == false) { if (! empty( $redux_builder_amp['amp-structured-data-placeholder-image']['url'] ) ) { $structured_data_image_url = $redux_builder_amp['amp-structured-data-placeholder-image']['url']; } $structured_data_image = $structured_data_image_url; $structured_data_height = intval($redux_builder_amp['amp-structured-data-placeholder-image-height']); $structured_data_width = intval($redux_builder_amp['amp-structured-data-placeholder-image-width']); $metadata['image'] = array( '@type' => 'ImageObject', 'url' => $structured_data_image , 'height' => $structured_data_height, 'width' => $structured_data_width, ); } |