2013-10-18 40 views
0

我正在創建一個網站,該網站集成了一個使用自定義帖子類型的投資組合,這是基於本教程完成的。wordpress query_posts alternative

到目前爲止,它正是我所需要的,除了一個小細節外,它的工作很棒。爲了從新的自定義帖子類型獲取帖子,本教程的作者使用了query_posts()codex。所以我的投資組合頁面的頂部看起來是這樣的:

<?php 
/* Template Name: Portfolio */ 
get_header(); 
query_posts('post_type=portfolio&posts_per_page=10'); 
?> 

我收集的是,這個聲明「得到的職位‘後型’投資組合,每頁顯示10」。我的問題是我無法從我的投資組合頁面獲取內容。看來,現在我的投資組合僅取出由自定義後類型的內容,我不能使用:

<?php while (have_posts()) : the_post(); ?> 
    <?php the_content(); ?> 
<?php endwhile; // end of the loop. ?> 

擺脫實際的頁面內容。

這就是我要做的,我把它換成:

query_posts('post_type=portfolio&posts_per_page=10'); 

有:

add_action('pre_get_posts', 'add_my_post_types_to_query'); 

function add_my_post_types_to_query($query) { 
    if (is_page(8) && $query->is_main_query()) 
     $query->set('post_type', array('portfolio')); 
    return $query; 
} 

這似乎是在正確的軌道,但它劇照不起作用。我沒有從我的自定義帖子類型中獲取帖子。

任何想法如何我可以修改此?我還在學習,所以很清楚,解釋將不勝感激。

謝謝!

回答

1

編輯pre_get_posts將取代原來的查詢,並且根本沒有您網頁的內容。如果您只想顯示投資組合帖子類型的內容,而不是投資組合頁面的內容,我只會推薦使用這種方法。

對於一般的後期查詢,建議使用WP_Query或get_posts。

http://codex.wordpress.org/Class_Reference/WP_Query

http://codex.wordpress.org/Template_Tags/get_posts

如果使用WP_Query功能wp_reset_postdata()會後的數據恢復到原來這樣你就可以得到您的原始網頁的內容。

$args = array(
    'posts_per_page' => 10, 
    'post_type' => 'portfolio', 

);  

// The Query 
$the_query = new WP_Query($args); 

// The Loop 
if ($the_query->have_posts()) { 
    while ($the_query->have_posts()) { 
     $the_query->the_post(); 
     echo '<li>' . get_the_title() . '</li>'; 
    } 
} else { 
    // no posts found 
} 
/* Restore original Post Data */ 
wp_reset_postdata(); 

現在,您就可以使用原來的循環,以顯示你的網頁的內容

<?php while (have_posts()) : the_post(); ?> 
    <?php the_content(); ?> 
<?php endwhile; // end of the loop. ?> 
+0

這個偉大的工程謝謝 – fred

+0

我用這種方法想知道是否有可能使用分頁? – fred

0

通常情況下,我堅持我的查詢的帖子在一個變量,像這樣:

$catid = get_cat_ID('My Category Name'); 

$args = array(
    'posts_per_page' => 5, 
    'orderby' => 'post_date', 
    'order' => 'DESC', 
    'post_type' => 'post', 
    'post_status' => 'publish', 
    'category' => $catid 
); 

$posts_array = get_posts($args); 

然後可以循環像這樣:

<?php foreach ($posts_array as $post) : setup_postdata($post);?> 
    <h1><?php the_title(); ?></h1> 
    <p><?php the_content(); ?></p> 
<?php endforeach; ?> 

最後,訪問你的頁面內容,您可以使用變量$post,它是由wordpress自動設置的。不需要添加比此更多的代碼來訪問您的頁面內容。

<?php foreach($posts as $post) : setup_postdata($post); ?> 
    <h1><?php the_title(); ?></h1> 
    <p><?php the_content(); ?></p> 
<?php endforeach; ?> 

foreach循環爲您的網頁內容是有點矯枉過正,並有更好的方法來做到這一點(最有可能至少),但我還沒有費心去看看它進一步呢!它雖然工作!