wordpress 将类别添加到自定义帖子类型并根据类别显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27896131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add categories to custom post type and display based on categories
提问by Pieter Goosen
I am working on a wordpress site with theme name flozo. It has a custom post type named work.
I wanted to display the works in my template based on each category.
我正在一个主题名称为flozo的 wordpress 网站上工作。它有一个名为work. 我想根据每个类别在我的模板中显示作品。
Here is the code:
这是代码:
<?php
$args = array( 'post_type' => 'work', 'posts_per_page' => 15 );
$loop = new WP_Query( $args );
$count = 0;
echo '<ul>';
while ( $loop->have_posts() ) : $loop->the_post();
$count++;
$class = ($count % 3 == 1) ? 'first' : '';
echo '<li class="'.$class.'">';
echo '<a href="';
the_permalink();
echo '">';
echo '<div class="overlay" style="background-color:'.ot_get_option( 'main_colour' ).';"></div>';
the_post_thumbnail('full');
echo '</a>';
echo '<br />';
echo '<h2><a href="';
the_permalink();
echo '">';
the_title();
echo '</a></h2>';
echo '<div class="entry-content">';
echo limit_words(get_the_excerpt(), '30');
echo '..</div>';
echo '</li>';
endwhile;
echo '</ul>';
?>
I've added
我已经添加
$args = array( 'post_type' => 'work', 'tag_ID' => 15 ,'posts_per_page' => 15 );
where 15is the id of my category, but it didn't work
15我的类别的 id在哪里,但它不起作用
I've also tried
我也试过
<?php
$catquery = new WP_Query( 'cat=15&posts_per_page=3' );
while($catquery->have_posts()) : $catquery->the_post();
?>
<ul class="last-cat">
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_post_thumbnail(); ?> <p><?php the_title(); ?></p><span><?php echo get_the_date(); ?></span></a></li></ul>
<?php endwhile; ?>
which also didn't help.
这也没有帮助。
Edit:
编辑:
The category url is
类别网址是
The post type registration code is :
帖子类型注册码为:
add_action('init', 'work_register');
function work_register() {
$labels = array(
'name' => _x('Work', 'post type general name'),
'singular_name' => _x('Work Item', 'post type singular name'),
'add_new' => _x('Add New', 'work item'),
'add_new_item' => __('Add New Work Item'),
'edit_item' => __('Edit Work Item'),
'new_item' => __('New Work Item'),
'view_item' => __('View Work Item'),
'search_items' => __('Search Work'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'menu_icon' => get_stylesheet_directory_uri() . '/article16.png',
'rewrite' => array( 'slug' => 'work', 'with_front'=> false ), 'capability_type' => 'post',
'hierarchical' => true,
'menu_position' => null,
'supports' => array('title','editor','thumbnail')
);
register_post_type( 'work' , $args );
register_taxonomy("categories", array("work"), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Category", "rewrite" => array( 'slug' => 'work', 'with_front'=> false )));
}
回答by Pieter Goosen
Both of the other answers are incorrect, specially the one from the OP. query_postsshould NEVER EVERbe used, it is even stated in the codex, so please, read the codex. Also, you should never replace the main query with custom queries.
其他两个答案都不正确,特别是来自 OP 的答案。query_posts应该永远不要使用,甚至在食品说明,所以,请阅读抄本。此外,您永远不应该用自定义查询替换主查询。
The solution is simple as I have described below and it is the correct wayof doing it.
解决方案很简单,正如我在下面描述的那样,这是正确的方法。
ORIGINAL ANSWER
原答案
You have a couple of flaws here
你这里有几个缺陷
For your custom post type to have an archive, you need to set the
has_archiveparameter totruein your custom post type registration arguments. Seeregister_post_type()If you are not going to use your custom post type like pages, set the
hierarchicalparameter tofalse. Setting this to true will considerably slow down your backend as your posts increase as Wordpress will try to build a tree for each post like it does for pagesNever use custom queries in place of the main query. It is always more troublesome and a waste of resources. See this postfor a full explanation on where and when to use custom queries correctly.
This point is an extension of the previous one. If you need to change the main query, use
pre_get_poststo do so. It uses the same exact parameters asWP_Queryas the main query usesWP_Queryto fetch posts. This is all explained in the linked post aboveYour main flaw in your custom query is your lack of understanding what the difference is between categories, tags and custom taxonomies. I have written a complete post ( which you can read here) on this and actually entered it into the codex as well. You are making use of a custom taxonomy, so the category parameters won't work. You need to use a
tax_queryfor custom taxonomies
要使您的自定义帖子类型具有存档,您需要在自定义帖子类型注册参数中将
has_archive参数设置为true。看register_post_type()如果您不打算使用自定义帖子类型(如页面),请将
hierarchical参数设置为false。将此设置为 true 会随着帖子的增加而大大减慢您的后端速度,因为 Wordpress 会尝试为每个帖子构建一棵树,就像它为页面所做的那样切勿使用自定义查询代替主查询。总是比较麻烦,浪费资源。有关在何处以及何时正确使用自定义查询的完整说明,请参阅此帖子。
这一点是上一点的延伸。如果您需要更改主查询,请使用
pre_get_posts。它使用与WP_Query主查询用于WP_Query获取帖子的完全相同的参数。这一切都在上面的链接帖子中进行了解释您自定义查询的主要缺陷是您缺乏了解类别、标签和自定义分类法之间的区别。我为此写了一篇完整的文章(您可以在此处阅读),并且实际上也将其输入了法典。您正在使用自定义分类法,因此类别参数将不起作用。您需要使用
tax_query自定义分类法
To solve your issue, follow the following steps
要解决您的问题,请按照以下步骤操作
Add the
has_achiveparameter to your arguments when registering your custom post type and set it totrue. If you want, set thehierarchicalparameter tofalseas well in your custom post type. (Do not set this for your custom taxonomy, this will make your taxonomy behave like normal tags)After this, flush your rewrite rules by visiting the permalink page under "Settings" and clicking "Update"
Visit your homepage just to make sure your new rules is saved
Delete your custom query and go back to the default loop. Your
archive-work.phpshould look like thisif( have_posts() ) { while( have_posts() ) { the_post(); // Your custom markup and template tags } }If you need to display posts from a specific term, create a
taxonomy.php,taxonomy-{$taxonomy}.phportaxonomy-{$taxonomy}-{$term}.phptemplate. Check the Template Hierarchyfor more info
has_achive在注册自定义帖子类型时将参数添加到您的参数中并将其设置为true. 如果需要,也可以在自定义帖子类型中将hierarchical参数设置false为。(不要为您的自定义分类设置此项,这会使您的分类表现得像普通标签)在此之后,通过访问“设置”下的永久链接页面并单击“更新”来刷新您的重写规则
访问您的主页只是为了确保您的新规则已保存
删除您的自定义查询并返回到默认循环。你
archive-work.php应该看起来像这样if( have_posts() ) { while( have_posts() ) { the_post(); // Your custom markup and template tags } }如果从特定术语需要显示的帖子,创建
taxonomy.php,taxonomy-{$taxonomy}.php或taxonomy-{$taxonomy}-{$term}.php模板。检查模板层次结构以获取更多信息
EDIT 1
编辑 1
If you only need to show a specific term on your custom post type archive term, after you have done the above, use pre_get_poststo alter the main query the correct way
如果您只需要在自定义帖子类型存档术语上显示特定术语,则在完成上述操作后,使用pre_get_posts以正确方式更改主查询
add_action( 'pre_get_posts', function ( $q ) {
if( !is_admin() && $q->is_main_query() && is_post_type_archive( 'work' ) ) {
$q->set( 'categories', 'slides' );
}
});
EDIT 2
编辑 2
Here is code to solve this
这是解决这个问题的代码
Copy and paste the following code in place of your code where you register your post type. I have added the has_archiveparameter. I have also changed the rewrite rule for your taxonomy to categories. It is really troublesome to have the same slug for both custom post type and taxonomy. This does not work by default and completely throws everything off target
复制并粘贴以下代码来代替您注册帖子类型的代码。我已经添加了has_archive参数。我还将您的分类法的重写规则更改为categories. 对于自定义帖子类型和分类法使用相同的 slug 真的很麻烦。默认情况下这不起作用,并且完全将所有内容都抛离目标
add_action( 'init', 'work_register' );
function work_register() {
$labels = array(
'name' => _x('Work', 'post type general name'),
'singular_name' => _x('Work Item', 'post type singular name'),
'add_new' => _x('Add New', 'work item'),
'add_new_item' => __('Add New Work Item'),
'edit_item' => __('Edit Work Item'),
'new_item' => __('New Work Item'),
'view_item' => __('View Work Item'),
'search_items' => __('Search Work'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'menu_icon' => get_stylesheet_directory_uri() . '/article16.png',
'rewrite' => array( 'slug' => 'work', 'with_front'=> false ),
'capability_type' => 'post',
'hierarchical' => true,
'has_archive' => true,
'menu_position' => null,
'supports' => array('title','editor','thumbnail')
);
register_post_type( 'work' , $args );
register_taxonomy( 'categories', array('work'), array(
'hierarchical' => true,
'label' => 'Categories',
'singular_label' => 'Category',
'rewrite' => array( 'slug' => 'categories', 'with_front'=> false )
)
);
register_taxonomy_for_object_type( 'categories', 'work' ); // Better be safe than sorry
}
In your archive-work.php, replace your custom query with this code
在您的 archive-work.php 中,用此代码替换您的自定义查询
<?php
$count = 0;
echo '<ul>';
while ( have_posts() ) : the_post();
$count++;
$class = ($count % 3 == 1) ? 'first' : '';
echo '<li class="'.$class.'">';
echo '<a href="';
the_permalink();
echo '">';
echo '<div class="overlay" style="background-color:'.ot_get_option( 'main_colour' ).';"></div>';
the_post_thumbnail('full');
echo '</a>';
echo '<br />';
echo '<h2><a href="';
the_permalink();
echo '">';
the_title();
echo '</a></h2>';
echo '<div class="entry-content">';
echo limit_words(get_the_excerpt(), '30');
echo '..</div>';
echo '</li>';
endwhile;
echo '</ul>';
?>
VERY IMPORTANT-> OK, now visit Settings >> Permalinksin the back end (admin area) and click Save Changes. This will flush your permalinks and set your new permalink structure
非常重要-> 好的,现在访问后端(管理区域)的Settings >> Permalinks并单击Save Changes。这将刷新您的永久链接并设置新的永久链接结构
You should now see all your post from your custom post type when you visit
您现在应该在访问时看到来自自定义帖子类型的所有帖子
回答by Pieter Goosen
<?php
query_posts( array( 'post_type' => 'work', 'categories' => 'slides' ) );
//the loop start here
if ( have_posts() ) : while ( have_posts() ) : the_post();
?>
<h3><?php the_title(); ?></h3>
<?php the_content(); ?>
<?php endwhile; endif; wp_reset_query(); ?>
i finally got it from hereperfect
我终于从这里得到它 完美的
回答by user3040610
Try with the below code,
试试下面的代码,
<?php
$args = array( 'posts_per_page' => 5,'post_type' => 'work','category' => 15 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ):?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach; ?>

