WordPressで投稿記事を取得する方法

IDで取得する方法

$post = get_post(417);
$post->post_title

投稿をすべて取得する方法

// 取得条件
$args = ['post_type' => 'post'];

// 取得
$the_query = new WP_Query($args);

if ( $the_query->have_posts() ) {
    foreach ( $the_query->posts as $post) {
        // これで表示して何が取れるか確認してみてください。
        print_r($post);

        // タイトルの場合は、こんな感じで取得できる
        print_r($post->post_title);
    }
}

複数IDで取得する方法

// 取得条件(複数ID)
$args = ['post__in' => [20, 204, 417, 1043]];

// 取得
$the_query = new WP_Query($args);

if ( $the_query->have_posts() ) {
    foreach ( $the_query->posts as $post) {
        // これで表示して何が取れるか確認してみてください。
        print_r($post);

        // タイトルの場合は、こんな感じで取得できる
        print_r($post->post_title);
    }
}

カテゴリのIDで取得する方法

$query = new WP_Query('cat=4');

カテゴリーのスラッグで取得する方法

$query = new WP_Query('category_name=staff');
参考

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です