2017-04-12 48 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函數中不起作用。你有解決這個問題嗎? –