2017-04-12 22 views
0

当我尝试在wordpress中使用get_post时,它总是返回最后一个帖子。get_post通过帖子标题总是返回最后插入的帖子

$the_code = 'couponcode'; 
$args = array(
    'post_title' => 'couponcode', 
    'post_type' => 'shop_coupon', 
    'post_status' => 'publish', 
    'numberposts' => 1 
); 
$my_code = get_posts($args); 

我这是怎么插入的优惠券后:

$coupon = array(
    'post_title' => 'couponcode', 
    'post_content' => '', 
    'post_status' => 'publish', 
    'post_author' => 1, 
    'post_type'  => 'shop_coupon' 
); 

$new_coupon_id = wp_insert_post($coupon); 

好吗显示了在后端管理。

+0

是啊,这是正确的。它应该返回给你什么? – Lutrov

+0

您正在查询以获取最后插入的一个。如果您需要更多数据,请更改“numberposts”值 –

+0

如何仅返回具有'couponcode'作为帖子标题的帖子。因为它返回具有不同标题的帖子。马上。 –

回答

2

试试这个简单的查询。

$posttitle = 'testcoupon'; 
$coupons = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_title = '" . $posttitle . "' AND post_type = 'shop_coupon'"); 

此代码测试OK

1

根据你的要求,你可以试试这个

$coupontitle = 'couponcode'; 
$postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_title = '" . $coupontitle . "'"); 
+0

现在它返回具有不同帖子标题的帖子。我希望它只返回具有'couponcode'作为帖子标题的那个。 –

+0

如果它没有显示帖子的标题,那么你也可以创建帖子类别“couponcode”,然后分配你的优惠券代码下的帖子,然后在你的args数组中传递类别id或name,像这样cat = 1或'category_name'=>'my -category-slug' –

+0

优惠券由woocommerece制成。我只想得到一个精确的post_title名称的单一优惠券。出于某种原因,args中的post_title在get_posts函数中不起作用。你有解决这个问题吗? –