[英]How can I display a list of categories and all their posts in WordPress?
我正在研究自定義WordPress主題。
我正在嘗試顯示自定義帖子類型的類別列表(作為標題),並且在每個類別標題下方,我想列出帖子標題和單個自定義字段。 我正在使用Types插件。 我知道一點點php並且有一些WordPress的經驗,但是還不足以正確地解決這個問題。
例:
自定義帖子類型: 菜單項
此帖子類型的自定義字段: 商品價格
類別: 三明治餡料
類別: 湯
所需結果:
三明治餡料
奶酪-£#。##
火腿-£#。##
金槍魚-£#。##
...
湯類
番茄
雞
蔬菜
想法是要動態添加新類別(例如,有一天他們可能會開始銷售熔膠),WP會在添加新類別時迭代這些類別,從而不必在新類別中進行硬編碼在添加它們的頁面上。
這是我到目前為止的內容:
<?php
$args = array(
'post_type' => 'menu-item',
'orderby' => 'name',
'parent' => 0
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
$posts = get_posts($args);
$item_price = types_render_field( "item-price" );
echo '<h2>' . $category->name . '</h2>';
?>
<ul><?php
foreach($posts as $post) {
?>
<li><?php the_title(); ?>, <?php echo $item_price; ?></li>
<?php
}
}
?>
我得到的是:
三文治
番茄,
瑞士芝士,
法國布里
法國布里
...
湯類
番茄£2.60
瑞士奶酪,2.60英鎊
法國干酪,2.60英鎊
法國干酪,2.60英鎊
任何幫助,將不勝感激!
更新
這似乎有所幫助:
<?php
$args = array(
'post_type' => 'menu-item'
);
$categories = get_categories( $args );
$posts = get_posts($args);
foreach ( $categories as $category ) {
echo '<h2>' . $category->name . '</h2>';
?>
<div class="menu-items-container">
<?php foreach($posts as $post) { ?>
<?php $item_price = types_render_field( "item-price" ); ?>
<?php if (in_category($category)) { ?>
<p><?php the_title(); ?>, <?php echo $item_price; ?></p>
<?php } ?>
<?php } ?>
</div>
<?php } ?>
這給了我一直在尋找的結果。 通過實驗和意外事故偶然發現了此修復程序,因此我知道這可能不是最佳實踐-歡迎提出改進的建議!
這樣的事情可能會更好,因為它不會遍歷每個類別的所有帖子:
<?php
$args = array(
'post_type' => 'menu-item'
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
echo '<h2>' . $category->name . '</h2>';
$args['category'] = $category->term_id;
$posts = get_posts($args); ?>
<div class="menu-items-container">
<?php foreach($posts as $post) { ?>
<?php $item_price = types_render_field( "item-price" ); ?>
<p><?php the_title(); ?>, <?php echo $item_price; ?></p>
<?php } ?>
</div>
<?php } ?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.