Dio*_*nes 10 wordpress custom-post-type
我希望有一个页面显示所有帖子,按类别分隔.想法是获取类别,然后遍历每个类别的所有帖子.由于我想使用自定义分类法作为类别迭代给定自定义类型的所有帖子,因此问题变得复杂.(运行Wordpress 3)
在我的functions.php中,我的自定义帖子类型注册为"视频",自定义分类注册为"video_types".
在我的自定义页面模板中,应该显示按类别排列的所有视频,这是不返回任何帖子的代码(他们在那里,我检查过):
<?php
$categories = get_categories(array(
'taxonomy' => 'video_types'
));
foreach ($categories as $cat):
?>
<section id="<?php $cat->slug ?>" class="video-category">
<?php
query_posts(array(
'cat' => $cat->cat_ID,
'posts_per_page' => -1
));
?>
<h2><?php single_cat_title(); ?></h2>
<p class="description"><?php echo category_description($cat->cat_ID); ?></p>
<?php while (have_posts()) : the_post(); ?>
<?php
$category = get_the_category();
echo $category[0]->cat_name;
?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<article class="video">
<h3><?php the_title(); ?></h3>
<p>
<?php the_content() ?>
</p>
</article>
<?php endwhile; ?>
</section>
<?php endforeach; ?>
Run Code Online (Sandbox Code Playgroud)
Dio*_*nes 15
Jeez,一旦你发现自定义分类法的每个项目都被称为一个术语(在nopress的wordpress docs中并不是很明显),它的搜索就更加简单了.没有所有自定义查询内容,此解决方案更容易理解.
<?php
// A term is an item of a taxonomy (e.g. "Promotional" could be a term for the taxonomy "video_type")
// ...so $categories could be $terms and it would still make sense
$categories = get_terms('taxonomy_name');
foreach( $categories as $category ):
?>
<section class="category-<?php echo $category ?>">
<h2><?php echo $category->name; // Print the cat title ?></h2>
<p class="description"><?php echo $category->description ?></p>
<div class="<?php echo $category->post_type ?>-list">
<?php
//select posts in this category (term), and of a specified content type (post type)
$posts = get_posts(array(
'post_type' => 'custom_post_type_name',
'taxonomy' => $category->taxonomy,
'term' => $category->slug,
'nopaging' => true, // to show all posts in this category, could also use 'numberposts' => -1 instead
));
foreach($posts as $post): // begin cycle through posts of this category
setup_postdata($post); //set up post data for use in the loop (enables the_title(), etc without specifying a post ID)
?>
// Now you can do things with the post and display it, like so
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h3><?php the_title(); ?></h3>
<?php
// Getting custom field data example
echo get_post_meta($post->ID, 'field_key', true);
?>
<?php the_content() ?>
</article>
<?php endforeach; ?>
</div>
</section>
<?php endforeach; ?>
Run Code Online (Sandbox Code Playgroud)
然后,通过在wordpress codex中搜索上述函数,可以填补理解上的任何空白.在上面的代码中,对于我的特定应用程序,custom_post_type_name将是video,而taxonomy_name将是video_type(或者video_types,我忘了).