WordPress>从自定义帖子类型

时间:2016-06-25 20:57:41

标签: wordpress post types filter

  1. Installed Custom Post Type UI wordpress plugin
  2. 创建了自定义帖子类型='产品'
  3. 使用
  4. 注册了自定义分类法类别(与类别不同)

    1。如何显示所有自定义帖子类型,并在上面使用过滤器标签作为类别的过滤器?

    2.如何通过自定义分类“类别”循环自定义模板并显示链接?

    HTML结构

    自定义帖子类型网址: /wp-admin/edit-tags.php?taxonomy=categories&post_type=products

    PHP

    <?php get_term( $term, $taxonomy, $output, $filter ) ?>
    
    <?php 
    $args=array(
      'name' => 'categories'
    );
    $output = 'products'; // or names
    $taxonomies=get_taxonomies($args,$output); 
    if  ($taxonomies) {
      foreach ($taxonomies  as $taxonomy ) {
        echo '<p>' . $taxonomy->name . '</p>';
      }
    }  
    ?>
    
    <?php 
    $args = array(
      'public'   => true,
      '_builtin' => false
    
    ); 
    $output = 'names'; // or objects
    $operator = 'and'; // 'and' or 'or'
    $taxonomies = get_taxonomies( $args, $output, $operator ); 
    if ( $taxonomies ) {
      foreach ( $taxonomies  as $taxonomy ) {
        echo '<p>' . $taxonomy . '</p>';
      }
    }
    

2 个答案:

答案 0 :(得分:2)

您可以执行此操作以获取自定义分类的所有条款:

https://developer.wordpress.org/reference/functions/get_terms/

$terms = get_terms( array(
    'taxonomy' => 'categories',
    'hide_empty' => false,
) );

foreach ( $terms as $term ) {
    $term_link = get_term_link( $term );
}

$term返回一个具有以下结构的数组:

array(
[0] => WP_Term Object
(
    [term_id] =>
    [name] =>
    [slug] =>
    [term_group] =>
    [term_taxonomy_id] =>
    [taxonomy] =>
    [description] =>
    [parent] =>
    [count] =>
    [filter] =>
)

$term_link会为您提供分类学术语存档的永久链接。

https://developer.wordpress.org/reference/functions/get_term_link/

关于如何实施过滤器标签的其他问题: 看看这个插件: https://wordpress.org/plugins/beautiful-taxonomy-filters/

答案 1 :(得分:1)

要查找与给定帖子类型相关的分类法,请使用WordPress get_object_taxonomies()函数,如下所示:

$taxonomies = get_object_taxonomies('post', 'objects');

$taxonomies将是WP_Taxonomy对象的数组。省略第二个参数以获取post_type子弹数组。

要通过自定义分类法进行查询,请创建一个新的WP_Query,如下所示:

$args = [
    'posts_per_page' => -1,
    'tax_query' => [
        [
            'taxonomy' => 'categories',
            'field' => 'slug',
            'terms' => ['your-term'],
        ],
    ],
];
$filterQuery = new WP_Query($args);

虽然可以使用register_post_type在post_types上声明分类法关联,但是该关联是可选的,并且非常弱。在内部,WordPress使用另一种方法,并为分类法分配post_types。

每个分类法都有一个object_type属性,该属性是它所知道的post_types的一个子标签数组。深入研究register_post_type源代码,我们看到它为register_taxonomy_for_object_type参数属性中的每个项目调用taxonomies,然后简单地将一个条添加到分类法的object_type数组中。这是唯一使用post_type的分类属性的方法。我更喜欢在注册分类法时声明post_types,因为它更接近WordPress的工作方式,并且误解了这种关联在过去曾给我带来很多麻烦。

相关问题