在wordpress企业网站中常常需要调用产品分类的产品列表,我们一般做模板的时候产品常常会自定义一个分类,下面介绍一下如何调用自定义分类调用的方法。
第一种方法:是通过get_posts函数 调用wordpress自定义分类文章。
在需要调用分类的模板中加入下面代码:
PHP
<?php
$posts = get_posts(array(
'numberposts' => '10', //输出的文章数量
'post_type' => 'product', //自定义文章类型名称
'tax_query'=>array(
array(
'taxonomy'=>'products', //自定义分类法名称
'terms'=>'10' //id为64的分类。也可是多个分类array(12,64)
)
),
)
); ?>
<ul>
<?php if($posts): foreach($posts as $post): ?>
<li><a href="<?php the_permalink(); ?>" target="_blank" ><?php the_title();?></a></li>
<?php wp_reset_postdata(); endforeach; endif;?>
</ul>
另外一种方法是通过WP_Query 函数调用 wordpress分类列表。
在需要调用的模板页面中加入下面代码进行调用:
PHP
<?php
$args = array(
'post_type' => 'product', //自定义文章类型名称
'showposts' => 10,
'tax_query' => array(
array(
'taxonomy' => 'products',//自定义分类法名称
'terms' => 64 //id为64的分类。也可是多个分类array(12,64)
),
)
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();?>
<li><a href="<?php the_permalink(); ?>" target="_blank" ><?php the_title();?></a></li>
<?php endwhile; wp_reset_query(); } ?>
上面代码的调用参数说明:
post_type 要调用的自定义文章类型的名称(必须和要调用的自定义分类法关联)
taxonomy 要调用的自定义分类法的名称
terms 要调用的自定义分类法下创建的分类目录ID
(在创建wordpress自定义分类的时候都会填写,跟创建时填写的保持一致就可以了)
发表评论