2011-11-08 48 views
0

因此,我有一段代碼抓取類別及其相符的帖子,並在循環之外列出它們(下圖)。我一直試圖讓帖子鏈接到#post- [ID]而不是永久鏈接 - 但我一直失敗。誰能幫忙?在Wordpress循環之外獲取帖子ID

<ul id="sidebar"> 
<?php 
    foreach(get_categories('orderby=ID&order=desc') as $cat) : 
    if(!$cat->parent) { 
    echo '<li class="title"><h2><a href="#">' . $cat->name . '</a></h2>'; 
    echo '<ul>'; 
    process_cat_tree($cat->term_id); 
      } 
    endforeach; 

    wp_reset_query(); //to reset all trouble done to the original query 
    // 
    function process_cat_tree($cat) { 
    $args = array('category__in' => array($cat), 'numberposts' => -1); 
    $cat_posts = get_posts($args); 
    $id = $post->ID; 

    global $post; 
    if($cat_posts) : 
    foreach($cat_posts as $menuPost) : 
    echo '<li'; 
    if ($menuPost->ID == $post->ID) { echo ' class="active"'; } 
    echo '>'; 
    echo '<a href="' . get_permalink($menuPost->ID) . '">' . $menuPost->post_title . '</a>'; 
    echo '</li>'; 
    endforeach; 
    endif; 

    echo '</ul></li>'; 
    } 
?> 

上面的代碼被輸出UL/LI標籤這樣的:

  • CATEGORY
    • 郵政
    • 郵政
    • 郵政
  • 類別
  • 類別
+0

闡述你的意思是「鏈接#後[ID]」什麼,我會相應地更新我的答案。 –

回答

0

誠然,我完全不明白你的「鏈接到#後[ID]」,但隨着問題的標題會是什麼意思:

如果您呼應鏈接時使用get_permalink(),你會得到永久鏈接 - 這就是那個功能所做的。

使用get_the_ID()相反,如果你想後返回的ID,或者the_ID()如果你想讓它顯示(the_ID()相同echo get_the_ID())。

編輯從這裏開始:

如果你與上面的代碼,否則快樂,改變

echo '<a href="' . get_permalink($menuPost->ID) . '">' . $menuPost->post_title . '</a>'; 

echo '<a href="#post-' . $menuPost->ID . '">' . $menuPost->post_title . '</a>'; 

應該做到這一點。

不過,我會去了解它,像這樣:

echo '<ul>'; 
$cat_args = array(
    'orderby' => 'name', 
    'order' => 'ASC' 
); 
$categories = get_categories($cat_args); 

foreach($categories as $category) { 
    echo '<li class="title"><h2><a href="#">' . $category->name . '</a></h2><ul>'; 
    // query posts of that category: 
    $query_args = array(
     'cat' => $category->cat_ID, 
     'posts_per_page' => -1 
    ); 
    $your_query = new WP_Query($query_args); 
    // loop through them: 
    while ($your_query->have_posts()) : $your_query->the_post(); 
     echo '<li><a href="#post-'; 
     the_ID(); 
     echo '">'; 
     the_title(); 
     echo '</a></li>'; 
    endwhile; 
    echo '</ul></li>'; 
    // Reset Post Data 
    wp_reset_postdata(); 
} 
echo '</ul>'; 
+0

我將執行Jquery選項卡。由於每個帖子都分配了一個帖子 - [id],所以我需要帖子分類列表中的鏈接指向#post- [id]。和FYI:我對Wordpress開發有點新鮮。 – user1036169

+0

@ user1036169好的。讓我們暫時忘記上面的代碼片段 - 這裏會有一些奇怪的事情發生。例如,我首先看到了一個'wp_reset_query();'而不是'new WP_Query()'。您需要(子)類別排序的所有帖子的列表。在每個列表項中,你想要什麼信息?請使用列表結構和列表項內容的非代碼示例更新您的問題。 –

+0

所以我換了 echo'' . $menuPost->post_title . ''; with echo'' . $menuPost->post_title . ''; 但它爲每個鏈接輸出相同的ID。任何想法是什麼造成的? – user1036169

相關問題