如何在wordpress中获取自定义帖子类型的最新帖子ID

问题描述 投票:1回答:4

我想获取WordPress中自定义帖子类型的最后一个帖子ID。为此,我尝试了此代码-

$args = array(
    'post_type' =>'soto_property',
    'posts_per_page' => 1,
    'orderby'=>'post_date',
    'order' => 'DESC',
);

$image_posts = get_posts($args);
foreach ( $image_posts  as $post ) {
    echo $post->ID;
}

但是它总是向我返回此自定义帖子类型的第一篇帖子ID。我也尝试过'order'=>'ASC',但是它给了我相同的结果。

我如何获得此CPT的最后一个帖子ID?

wordpress post custom-post-type
4个回答
1
投票

您可以使用wp_get_recent_posts功能。这是一个示例函数:

$args = array(
    'post_type' =>'soto_property',
    'posts_per_page' => 1
);
$recent_post = wp_get_recent_posts($args, OBJECT);

检查function reference page in codex了解更多信息。


0
投票

尝试使用WP_Query

$args=array(
      'post_type' => 'soto_property',
      'posts_per_page' => 1,
      'caller_get_posts'=> 1,
      'orderby' => 'id',
      'order'   => 'DESC'
      );

    $query = new WP_Query($args);

    foreach ($query as $key) {

        $last_soto_property = $key->ID;
    }
var_dump($last_soto_property);

这将显示您的最后一个自定义帖子类型的ID。


-1
投票

您的PHP代码包含一个小错误:

posts_per_page设置为1。它应该高于一个。这就是为什么您从查询的结果中仅得到一个结果的原因。

因此,可以用'posts_per_page' => 1代替'posts_per_page' => your_desired_number_of_post_here >>

您的完整代码应如下所示:

$args = array(
    'post_type' =>'soto_property',
    'posts_per_page' => your_desired_number_of_post_here,
    'orderby'=>'post_date',
    'order' => 'DESC',
     );

   $image_posts = get_posts($args);
   foreach ( $image_posts  as $post )
   {
       echo $post->ID;
   }

-1
投票

我使用下面的$wpdb查询获得了我最后插入的帖子ID-

© www.soinside.com 2019 - 2024. All rights reserved.