前提・実現したいこと
Wordpressで構築しているサイトにOGPタグの設定したく、
フックをfunctions.phpに記述しています。
投稿記事(single.php)の場合に、
①アイキャッチ画像
↓ なければ…
②本文欄の画像(1枚目)
↓ なければ…
③デフォルト画像
の優先順番でog:image画像を取得したいです。
発生している問題・エラーメッセージ
タグは問題なく吐き出しされ、
画像も意図したものが取得できているのですが、
本文欄に画像がない場合に、
html
1<b>Notice</b>: Undefined offset: 0 in ....
というエラーがheadタグ内に出てしまいます。本文欄に画像があれば、エラーは出ません。
エラーが出ないよう、コードを修正をしたいです。
該当のソースコード
php
1function my_meta_ogp() { 2 if (is_single()) { 3 global $post; 4 $ogp_title = ''; 5 $ogp_descr = ''; 6 $ogp_url = ''; 7 $ogp_img = ''; 8 $insert = ''; 9 10 //og:title、og:des 11 setup_postdata($post); 12 $ogp_title = $post - > post_title; 13 $ogp_descr = mb_substr(get_the_excerpt(), 0, 100); 14 $ogp_url = get_permalink(); 15 wp_reset_postdata(); 16 17 //og:type 18 $ogp_type = 'article'; 19 20 //og:image 21 if ( has_post_thumbnail() ) { 22 $ps_thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full'); 23 $ogp_img = $ps_thumb[0]; 24 } else { 25 //本文に画像があるか判別 26 $first_img = ''; 27 ob_start(); 28 ob_end_clean(); 29 $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 30 $first_img = $matches [1] [0]; 31 if(empty($first_img)) { 32 //本文に画像がない 33 $ogp_img_directory_url = get_stylesheet_directory_uri(); 34 $ogp_img = ''.$ogp_img_directory_url.'/common/img/ogp.jpg'; //デフォルトのOGP画像 35 } else { 36 //本文に画像がある 37 $ogp_img = $first_img; 38 } 39 } 40 41 //出力するOGPタグをまとめる 42 $insert. = '<meta property="og:title" content="'.esc_attr($ogp_title).'" />'."\n"; 43 $insert. = '<meta property="og:description" content="'.esc_attr($ogp_descr).'" />'."\n"; 44 $insert. = '<meta property="og:type" content="'.$ogp_type.'" />'."\n"; 45 $insert. = '<meta property="og:url" content="'.esc_url($ogp_url).'" />'."\n"; 46 $insert. = '<meta property="og:image" content="'.esc_url($ogp_img).'" />'."\n"; 47 $insert. = '<meta property="og:site_name" content="'.esc_attr(get_bloginfo('name')).'" />'."\n"; 48 49 echo $insert; 50 } 51} 52//head内にOGPを出力 53add_action('wp_head', 'my_meta_ogp'); 54
自分で試したこと・調べたこと
php
1$first_img = $matches [1] [0];
に問題があるとエラーは言っていて、
- リスト空の配列に対して要素の取得を行おうとする
- 配列のサイズを超えた範囲にアクセスしてしまう
ということが原因…というところまで分かり、その意味もなんとなくイメージはつかめるのですが、
具体的にどこをどのように修正したらよいのか、私の知識では検討がつかずつまづいております。(><)
どなたか、ご教示いただけないでしょうか。
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/03/21 05:01
2019/03/21 08:20