我想在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。
答案 0 :(得分:1)
您可以使用wp_get_recent_posts
功能。
这是一个示例函数:
$args = array(
'post_type' =>'soto_property',
'posts_per_page' => 1
);
$recent_post = wp_get_recent_posts($args, OBJECT);
答案 1 :(得分: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。
答案 2 :(得分:-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;
}
答案 3 :(得分:-1)
我使用$wpdb
查询获得了上次插入的帖子ID,如下所示 -
global $wpdb;
$lastrowId=$wpdb->get_col( "SELECT ID FROM wp_posts where post_type='soto_property' ORDER BY post_date DESC " );
$lastPropertyId=$lastrowId[0];