[WP] WordPressの投稿編集画面にカスタムフィールドを配置して同じタグを持つ他の投稿のURLを自動挿入すPHPコード[2023/11/26]

質問2

「wordpressにおいて投稿の編集画面にカスタムフィールドを設定したとして,このカスタムフィールドに,この投稿につけられたタグと同じタグを持つ投稿のURLを張り付けるPHPコードを教えてください」

回答2

まず、カスタムフィールドを追加するには、functions.phpに以下のようなコードを記述します。12

AI で生成されたコード。ご確認のうえ、慎重にご使用ください。FAQ で詳細を確認

// カスタムフィールドのメタボックスを追加する関数
function add_related_posts_field() {
    // 投稿タイプを指定する(post, page, custom_post_typeなど)
    $post_type = 'post';
    // カスタムフィールドのメタボックスのIDを指定する
    $meta_box_id = 'related_posts';
    // カスタムフィールドのメタボックスのタイトルを指定する
    $meta_box_title = '関連記事';
    // カスタムフィールドのメタボックスを表示する場所を指定する(normal, side, advancedなど)
    $context = 'normal';
    // カスタムフィールドのメタボックスの優先度を指定する(high, low, defaultなど)
    $priority = 'high';
    // カスタムフィールドのメタボックスのコールバック関数を指定する
    $callback = 'show_related_posts_field';
    // カスタムフィールドのメタボックスを追加する
    add_meta_box($meta_box_id, $meta_box_title, $callback, $post_type, $context, $priority);
}

// カスタムフィールドのメタボックスのコールバック関数
function show_related_posts_field() {
    // グローバル変数$postを使えるようにする
    global $post;
    // カスタムフィールドのキーを指定する
    $custom_field_key = 'related_posts';
    // カスタムフィールドの値を取得する
    $custom_field_value = get_post_meta($post->ID, $custom_field_key, true);
    // nonceフィールドを生成する(セキュリティ対策)
    wp_nonce_field('save_related_posts_field', 'related_posts_nonce');
    // カスタムフィールドの入力フォームを表示する
    echo '<label for="related_posts">関連記事のURLを入力してください(複数ある場合は改行で区切ってください)</label>';
    echo '<textarea id="related_posts" name="related_posts" rows="5" cols="50">' . esc_textarea($custom_field_value) . '</textarea>';
}

// カスタムフィールドの値を保存する関数
function save_related_posts_field($post_id) {
    // nonceフィールドの値を取得する
    $nonce = isset($_POST['related_posts_nonce']) ? $_POST['related_posts_nonce'] : '';
    // nonceフィールドの値を検証する(セキュリティ対策)
    if (!wp_verify_nonce($nonce, 'save_related_posts_field')) {
        return $post_id;
    }
    // 自動保存の場合は処理をしない
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }
    // ユーザーが投稿を編集できる権限があるかチェックする
    if (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }
    // カスタムフィールドのキーを指定する
    $custom_field_key = 'related_posts';
    // カスタムフィールドの値を取得する
    $custom_field_value = isset($_POST['related_posts']) ? $_POST['related_posts'] : '';
    // カスタムフィールドの値を保存する
    update_post_meta($post_id, $custom_field_key, $custom_field_value);
}

// アクションフックに関数を登録する
add_action('add_meta_boxes', 'add_related_posts_field');
add_action('save_post', 'save_related_posts_field');
次に、このカスタムフィールドに、この投稿につけられたタグと同じタグを持つ投稿のURLを自動で張り付けるには、以下のようなコードをfunctions.phpに追加します。3

PHP
AI で生成されたコード。ご確認のうえ、慎重にご使用ください。FAQ で詳細を確認。

// カスタムフィールドに関連記事のURLを自動で張り付ける関数
function auto_related_posts_field($post_id) {
    // カスタムフィールドのキーを指定する
    $custom_field_key = 'related_posts';
    // カスタムフィールドの値を取得する
    $custom_field_value = get_post_meta($post_id, $custom_field_key, true);
    // カスタムフィールドの値が空の場合のみ処理をする
    if (empty($custom_field_value)) {
        // この投稿につけられたタグのIDの配列を取得する
        $tags = wp_get_post_tags($post_id, array('fields' => 'ids'));
        // タグがある場合のみ処理をする
        if ($tags) {
            // この投稿と同じタグを持つ投稿のクエリを作成する
            $query = new WP_Query(array(
                'tag__in' => $tags, // タグのIDの配列
                'post__not_in' => array($post_id), // この投稿を除外する
                'posts_per_page' => 5, // 最大5件取得する
                'orderby' => 'rand', // ランダムに並べる
                'no_found_rows' => true, // ページネーションをしない
            ));
            // クエリにマッチした投稿がある場合のみ処理をする
            if ($query->have_posts()) {
                // 関連記事のURLの配列を作成する
                $related_posts = array();
                // クエリのループを開始する
                while ($query->have_posts()) {
                    // 投稿データをセットする
                    $query->the_post();
                    // 投稿のURLを取得して配列に追加する
                    $related_posts[] = get_permalink();
                }
                // クエリのループをリセットする
                wp_reset_postdata();
                // 配列を改行で区切って文字列にする
                $related_posts = implode("\n", $related_posts);
                // カスタムフィールドの値として保存する
                update_post_meta($post_id, $custom_field_key, $related_posts);
            }
        }
    }
}

// save_postフックに関数を登録する
add_action('save_post', 'auto_related_posts_field');

次に、このカスタムフィールドに、この投稿につけられたタグと同じタグを持つ投稿のURLを自動で張り付けるには、以下のようなコードをfunctions.phpに追加します。3

AI で生成されたコード。ご確認のうえ、慎重にご使用ください。FAQ で詳細を確認
// カスタムフィールドに関連記事のURLを自動で張り付ける関数
function auto_related_posts_field($post_id) {
    // カスタムフィールドのキーを指定する
    $custom_field_key = 'related_posts';
    // カスタムフィールドの値を取得する
    $custom_field_value = get_post_meta($post_id, $custom_field_key, true);
    // カスタムフィールドの値が空の場合のみ処理をする
    if (empty($custom_field_value)) {
        // この投稿につけられたタグのIDの配列を取得する
        $tags = wp_get_post_tags($post_id, array('fields' => 'ids'));
        // タグがある場合のみ処理をする
        if ($tags) {
            // この投稿と同じタグを持つ投稿のクエリを作成する
            $query = new WP_Query(array(
                'tag__in' => $tags, // タグのIDの配列
                'post__not_in' => array($post_id), // この投稿を除外する
                'posts_per_page' => 5, // 最大5件取得する
                'orderby' => 'rand', // ランダムに並べる
                'no_found_rows' => true, // ページネーションをしない
            ));
            // クエリにマッチした投稿がある場合のみ処理をする
            if ($query->have_posts()) {
                // 関連記事のURLの配列を作成する
                $related_posts = array();
                // クエリのループを開始する
                while ($query->have_posts()) {
                    // 投稿データをセットする
                    $query->the_post();
                    // 投稿のURLを取得して配列に追加する
                    $related_posts[] = get_permalink();
                }
                // クエリのループをリセットする
                wp_reset_postdata();
                // 配列を改行で区切って文字列にする
                $related_posts = implode("\n", $related_posts);
                // カスタムフィールドの値として保存する
                update_post_meta($post_id, $custom_field_key, $related_posts);
            }
        }
    }
}

// save_postフックに関数を登録する
add_action('save_post', 'auto_related_posts_field');

1. ja.wordpress.org 2. shu-sait.com 3. miya-system-works.com 4. qiita.com

人気順