1,011 views
この記事は最終更新から 1404日 が経過しています。
1. やりたいこと
ブログ記事の URLを知っている。
ここからブログ記事の投稿IDを知りたい。
すなわち…
DB上の wp_posts テーブルに保存されている当該記事のレコードの ID カラムの値を取得したい。
2. やってみる
WORDPRESSの url_to_postid( $url ) 関数で取得できる。
$urlは記事のURLなので、ページ表示中に get_the_permalink() で取得出来る。
試しに簡単なプラグインを作ってみた。
ショートコードを貼り付けておけば、そこに表示中ページの投稿IDを表示してくれる。
if(class_exists('show_postID')){
$show_postID= new show_postID();
}
class show_postID {
//////////////////////////////////////////////////////////////////////
public function __construct() {
// ショートコードを登録
add_shortcode('show_postID', array($this, 'proc_shortcode'));
// テキストウィジェットの中でショートコードを実行可能に設定
add_filter('widget_text', 'do_shortcode');
}
//////////////////////////////////////////////////////////////////////
public function proc_shortcode(){
$current_url = get_the_permalink();
$post_id = url_to_postid( $current_url );
return <<< EOM
<p>ID:{$post_id}</p>
EOM;
}
}
ここ(↓)に表示されているのが、本記事の投稿IDだ。
ID:2013
上記のプラグインで表示させている。
アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済2026-01-29: 0回 2026-01-28: 0回 2026-01-27: 1回 2026-01-26: 0回 2026-01-25: 0回 2026-01-24: 0回 2026-01-23: 0回