2016-11-08 62 views
0

我在自定義頁面模板上使用get_posts以列出用戶是其作者的特定類型的帖子(本例中爲business)。 這裏是我想要的代碼:Wordpress get_posts無法正常工作

$args = array(
    'author' => get_current_user_id(), 
    'post_type' => 'business', 
    'posts_per_page' => -1, 
    'post_status' => array(
     'publish', 
     'pending', 
    ) 
); 
$listings = get_posts($args); 

然而,這種由用戶返回無論類型的所有職位。如果我刪除了author參數,我會得到所需類型的所有帖子,而無需考慮作者。 get_current_user_id()確實會返回正確的用戶標識,但我嘗試在代碼中添加標識以及獲得相同的結果。

有沒有人知道爲什麼會發生這種情況?

我使用WP 4.6.1

UPDATE: SQL日誌顯示了以下

如果我使用author參數:

SELECT wp_posts.* 
FROM wp_posts 
WHERE 1=1 
AND wp_posts.post_author IN (1) 
AND wp_posts.post_type IN ('post', 'project', 'profile', 'campaign') 
AND ((wp_posts.post_status = 'publish' 
OR wp_posts.post_status = 'pending')) 
ORDER BY wp_posts.post_date DESC 

如果我離開author參數出來:

SELECT wp_posts.* 
FROM wp_posts 
WHERE 1=1 
AND wp_posts.post_type = 'business' 
AND ((wp_posts.post_status = 'publish' 
OR wp_posts.post_status = 'pending')) 
ORDER BY wp_posts.post_date DESC 

而且,這裏是自定義文章類型聲明:

register_post_type('business', 
    array(
     'labels' => array(
     'name'   => __('Businesses'), 
     'singular_name' => __('Business'), 
     'add_new'  => __('Add New Business'), 
     'add_new_item' => __('Add New Business'), 
     'edit_item'  => __('Edit Business') 
    ), 
     'public'  => true, 
     'has_archive' => true, 
     'menu_icon' => 'dashicons-store', 
     'supports' => array('thumbnail', 'title', 'editor', 'author') 
    ) 
); 

我在這裏損失...

+0

你的論點看起來是正確的。你可以顯示'register_post_type'代碼,所以我們可以看到你用來註冊帖子的類型嗎? –

+1

另外,[查看SQL語句]可能很有用(http://wordpress.stackexchange.com/questions/110266/how-to-print-the-excuted-sql-right-after-its-execution)當你執行這個'get_posts'時運行。 –

回答

0
<?php 
global $current_user; 


$args = array(
    'author' => $current_user->ID, 
    'post_type' => 'business', 
    'posts_per_page' => -1, 
    'post_status' => 'publish' 
); 
$listings = get_posts($args); 
?> 
+0

請避免使用純代碼的答案,並提供代碼解釋。 –