0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPress ユーザー毎の最新記事のURLをデータベースに保存する

Last updated at Posted at 2019-10-29

WordPressで、ユーザー毎の最新記事URLをデータベースに保存する方法です。
もちろん、ユーザーを指定して最新の投稿記事を取ってくることは可能ですが、ユーザー数が多くなった場合に、ユーザーのメタ情報に最新記事URLを保存しておいたほうがサーバ負荷を抑えられるかな、という考えです。

前提

[「WordPressユーザーのためのPHP入門 はじめから、ていねいに。」] (https://php4wordpress.calculator.jp/)を読了した程度のPHP、WordPressの知識

コード

以下のようなコードになります。(コードはGPL ver.2 or later)

add_action( 'publish_post', 'setup_latest_post_url', 10, 2 );

function setup_latest_post_url( $id, $post ) {
	$permalink = get_permalink( $id );
	$uid = intval($post->post_author);
	update_user_meta( $uid, "latestpermalink", $permalink);
}

以下、ざっくりと説明をします。

まず、投稿を公開するときに、ユーザーの情報を更新したいので、publish_postアクションフックを活用します。

publish_postアクションフックでは、投稿IDと、投稿オブジェクトをパラメータとして渡すので、これらを活用します。

get_permalink()は、投稿URLを取得する関数です。また投稿者のユーザーIDは、投稿オブジェクトのpost_authorプロパティで取得します。

ユーザー情報を更新する関数はupdate_user_metaが用意されているので、こちらを使います。

//            ↓アクションフック名
add_action( 'publish_post', 'setup_latest_post_url', 10, 2 );
//                              ↑アクションフックで実行する関数名

                              // ↓ 投稿ID
function setup_latest_post_url( $id, $post ) {
                                    // ↑投稿オブジェクト

        //            ↓ 投稿ID → 投稿URL へ変換する
	$permalink = get_permalink( $id );

        //             ↓投稿オブジェクトから投稿者のユーザーIDを取得する
	$uid = intval($post->post_author);

        // ↓ ユーザーのメタ情報を変更する
	update_user_meta( $uid, "latestpermalink", $permalink);
}

このようにすると、『ユーザーが投稿を公開したとき、そのユーザーのメタ情報latestpermalinkに、投稿のURLを保存する』という処理が可能になります。

(※予約投稿の場合に期待通りに動くかどうかは未検証※)

今回の記事は、読書好きが次に読む本を紹介するブックレコメンド向けに作成したコードを共有しています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?