故事是这样的:我制作了一个包含3种自定义帖子类型的产品目录:
- Product
- Filegroup (Child of Product)
- File (Child of Filegroup)
在产品页面上,应显示一个列表,其中包含文件组标题和正确文件组下的松散文件。但它显示了父母双方的孩子
现在是这样的:
- Filegroup 1
- File 3 (child of Filegroup 2)
- File 1 (child of Filegroup 1)
- File 2 (child of Filegroup 1)
- Filegroup 2
- File 3 (child of Filegroup 2)
- File 1 (child of Filegroup 1)
- File 2 (child of Filegroup 1)
它需要:
- Filegroup 1
- File 1 (child of Filegroup 1)
- File 2 (child of Filegroup 1)
- Filegroup 2
- File 3 (child of Filegroup 2)
我的当前脚本
<?php
$childargs = array(
\'post_type\' => \'filegroup\',
\'numberposts\' => -1,
\'order\' => \'ASC\',
);
$child_posts = get_posts($childargs);
foreach ($child_posts as $child_post){
$parentid = $child_post->ID;
?>
<ul>
<li><strong><?php echo $child_post->post_title; ?></strong></li>
<?php
$childargs2 = array(
\'post_type\' => \'file\',
\'numberposts\' => -1,
\'post_parent\' => \'0\'
);
$child_posts2 = get_posts($childargs2);
foreach ($child_posts2 as $child_post){
?>
<li><?php echo $child_post->post_title; ?></li>
<?php
}
?>
</ul>
<?php
}
?>
最合适的回答,由SO网友:Cas 整理而成
当我忘记了所有糟糕的代码时,我决定从头开始:)于是我找到了解决方案:
<?php
// Define variables
$post_type = \'file\';
$taxonomy = \'file-category\';
$taxonomy_terms = get_terms($taxonomy);
global $current_page_id;
$current_page_id = get_the_ID();
// Start if
if ($taxonomy_terms) {
// Start Foreach
foreach ($taxonomy_terms as $taxonomy_term) {
// Start arguments for getting the posts and taxonomy
$arguments = array(
\'post_type\' => $post_type,
"$taxonomy" => $taxonomy_term->slug,
\'post_status\' => \'publish\',
\'posts_per_page\' => -1,
\'caller_get_posts\' => 1,
\'post_parent\' => 0,
);
// End arguments
// Set query to null
$new_query = null;
// Start WP_Query
$new_query = new WP_Query($arguments);
// Start fetching posts if
if($new_query->have_posts() ) {
?>
<ul>
<?php
echo \'<li><strong>\' . $taxonomy_term->name . \'</strong></li>\';
// Start while
while($new_query->have_posts()) : $new_query->the_post();
// Get parent id
$parent_id = wpcf_pr_post_get_belongs(get_the_ID(), \'product\');
// Start if $parent_id and $current page id are equal
if($parent_id == $current_page_id){
?>
<li>
<a href="<?php echo types_render_field("file-uploads", array( "raw" => "true") ); ?>">
<span><?php the_title(); ?></span><?php echo(types_render_field("lang", array())); ?>
</a>
</li>
<?php
// End if $parent_id and $current page id are equal
}
// End while
endwhile;
?>
</ul>
<?php
// End fetching if
}
// End foreach
}
// End if
}
?>