1
1

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.

wp_posts テーブル中で最新の行 ID を取得する

Last updated at Posted at 2014-12-26

post テーブルにおける、無条件で最新の ID を取得する。

前提

  • 外部の PHP プログラムから WordPress を操作する
  • wp-load.php が読み込まれている

本題

生に近い SQLクエリを DB に投げて取得する。

wp-load.php をロードしていると $wpdb というグローバル変数がセットされる。

Class Reference/wpdb « WordPress Codex

これを使って

global $wpdb;
$postIdMax = $wpdb->get_var("SELECT MAX(ID) AS postIdMax FROM {$wpdb->posts}");

のようにする。先述の " 生に近い SQL クエリ " と書いたのは、上のようにクエリ中で
$wpdb->posts などと書けば、テーブル名を直接していしなくて良いから。

WordPress のデフォルトのテーブル名だと wp_something となるが、独自にテーブル接頭辞をカスタムして wp_abcdefg_something などとしている場合や、開発環境と本番環境でテーブル名が異なる場合でも、 $wpdb->posts のお陰でコードを分けなくて済むという利点がある。

以上。

余談

当初試みた処理はをメモしておく。失敗したけど。

$wp_get_recent_posts_arg = [
    'numberposts' => 1,
    'offset' => 0,
    'category' => null,
    'orderby' => 'post_id',
    'order' => 'DESC',
    'include' => null,
    'exclude' => null,
    'meta_key' => null,
    'meta_value' => null,
    'post_type' => 'post',
    'post_status' => 'draft, publish, future, pending, private, auto-draft, inherit',
    'suppress_filters' => false,
];
$postId = wp_get_recent_posts($wp_get_recent_posts_arg);
var_dump($postId[0]);

これだと auto-draft なども含めた本当の最新 ID は取れなかった。
wp_get_recent_posts() はあくまで最新の投稿データである ID を取得するものなのかも。

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?