ワードプレスの投稿画面と固定ページの管理画面にカスタムフィールド追加しh1を取得する方法
タイトルのままですが、
WordPressでページごとにh1を変えたくて、
また、カスタムフールドに入れたキーワードでh1にしたい場合、以下のようにすると出来ます!
functions.phpに以下を追記してください!
// SEO関係 h1とか
// カスタムフィールド追加
add_action('admin_menu', 'add_custom_fields');
add_action('save_post', 'save_custom_fields');
function add_custom_fields() {
add_meta_box( 'my_sectionid', 'カスタムフィールド', 'my_custom_fields', 'post'); // 投稿管理画面に表示
add_meta_box( 'my_sectionid', 'カスタムフィールド', 'my_custom_fields', 'page'); // 固定ページ管理画面に表示
}
function my_custom_fields() {
global $post;
$meta_keywords = get_post_meta($post->ID,'meta_keywords',true);
$h1 = get_post_meta($post->ID,'h1',true);
$noindex = get_post_meta($post->ID,'noindex',true);
if($noindex==1){ $noindex_c="checked";}
else{$noindex_c= "/";}
echo '<p>キーワード(meta keyword)カンマ区切り。2〜6つまで<br />';
echo '<input type="text" name="meta_keywords" value="'.esc_html($meta_keywords).'" size="40" /></p>';
echo '<p>大見出し(h1)40文字以内を推奨<br />';
echo '<input type="text" name="h1" value="'.esc_html($h1).'" size="50" /></p>';
echo '<p>低品質コンテンツならチェックすると「noindex」に<br />';
echo '<input type="checkbox" name="noindex" value="1" ' . $noindex_c . '> noindex</p>';
}
// カスタムフィールドの値を保存
function save_custom_fields( $post_id ) {
if(!empty($_POST['meta_keywords']))
update_post_meta($post_id, 'meta_keywords', $_POST['meta_keywords'] );
else delete_post_meta($post_id, 'meta_keywords');
if(!empty($_POST['h1']))
update_post_meta($post_id, 'h1', $_POST['h1'] );
else delete_post_meta($post_id, 'h1');
if(!empty($_POST['noindex']))
update_post_meta($post_id, 'noindex', $_POST['noindex'] );
else delete_post_meta($post_id, 'noindex');
}
// SEO関係 h1とか ここまで!
それから、
header.phpとかでh1を表示させた居場所に、以下を記載してください!
<?php $custom = get_post_custom(); ?>
<?php if(empty($custom['h1'][0])){ $custom['h1'][0] = get_the_title(); } ?>
<h1><?php echo $custom['h1'][0] ?></h1>
これでOKです!
関連記事はこちら!
スポンサーリンク
タグ:h1, SEO, カスタムフィールド追加






