我正在开发自定义 WordPress 主题。
我正在尝试显示自定义帖子类型的类别列表(作为标题),并且在每个类别标题下方我想列出帖子标题和一个自定义字段。我正在使用类型插件。我懂一点 php 并有一些 WordPress 经验,但还不足以正确解决这个问题。
示例:
Custom Post Type: Menu Item
Custom Field for This Post Type: Item Price
Category: Sandwich Fillings
Category: Soups
Desired result:
Sandwich Fillings
Cheese - £#.##
Ham - £#.##
Tuna - £#.##
...
Soups
Tomato
Chicken
Vegetable
想法是动态添加新类别(例如,有一天他们可能会开始销售融化),并且 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
}
}
?>
我得到的是这样的:
Sandwiches
Tomato,
Swiss Cheese,
French Brie,
French Brie,
...
Soups
Tomato, £2.60
Swiss Cheese, £2.60
French Brie, £2.60
French Brie, £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 } ?>
关于php - 如何在 WordPress 中显示类别列表及其所有帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381626/