按分类列出所有自定义帖子类型的帖子

时间:2020-05-28 20:15:48

标签: javascript php wordpress list

我正在尝试通过分类学获取所有自定义帖子类型的帖子列表,我在此代码停留了3天,现在我和父亲一起学习,他给了我一个提示,为什么我的代码不起作用,他一个人说我有太多的参数,我将向您展示代码,我希望任何人都可以帮助我理解它为什么不起作用的原因,也许如果您真的对英语的代码进行了解释

print_r(Array(
    "1"=>"first",
    "2"=>"second"
    ));
// just try to remove args that you don't need 
//actually you need only one
$args = array(
    'tax_query' => array(
            'taxonomy' => 'your-custom-taxonomy',
            'field' => 'slug',
            'terms' => array( 'your-term' )
    ),
    'post_type' => 'your-post-type'
);
$loop = new WP_Query($args);
     if($loop->have_posts()) {
    $term = $wp_query->queried_object;
     while($loop->have_posts()) : $loop->the_post();
        //Output what you want      
   echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
      endwhile;
}

1 个答案:

答案 0 :(得分:0)

  1. 因此,您有一个名为your-post-type的自定义帖子类型
  2. 您有一个名为your-custom-taxonomy的自定义分类法,您
  3. 希望获得所有带有分类术语集your-term的帖子。

您正在通过设置参数来正确执行操作。

通知:如果您要获取所有自定义帖子类型的帖子,则不需要整个代码'tax_query'的一部分。

我添加了一些注释来描述代码在做什么:

$args = array( // define your arguments for query
    'post_type' => 'your-post-type', // standard post type is 'post', you use a custom one
    'tax_query' => array( // you check for taxonomy field values
        array(
            'taxonomy' => 'your-custom-taxonomy', // standard is 'category' you use a custom one
            'field'    => 'slug', // you want to get the terms by its slug (could also use id)
            'terms'    => 'your-term', // this is the taxonomy term slug the post has set
        ),
    ),
);
$loop = new WP_Query( $args ); // get post objects

// The Loop
if ( $loop ->have_posts() ) { // check if you received post objects
    echo "<ul>"; // open unordered list
    while ( $loop ->have_posts() ) { // loop through post objects
        $loop ->the_post();
            echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>'; // list items
    }
    echo "</ul>"; // close unordered list
    /* Restore original Post Data */
    wp_reset_postdata(); // reset to avoid conflicts
} else {
    // no posts found
}

希望这会有所帮助!


编辑:如果您不知道如何使用WP_Query

此代码将使您的wordpress帖子按其标题排序,并输出标题和内容。将其放在您主题的模板文件中(了解有关模板文件的信息:https://developer.wordpress.org/themes/basics/template-hierarchy/)。

<?php 

$args = array(
 'post_type' => 'post',
 'posts_per_page' => -1, // limit the number of posts if you like to
 'orderby' => 'title',
 'order' => 'ASC'
);

$custom_query = new WP_Query($args); 

if ($custom_query->have_posts()) : while($custom_query->have_posts()) : $custom_query->the_post(); ?> 
  <h1><?php the_title(); ?></h1> 
  <?php the_content();?>
<?php endwhile; else : ?> 
  <p>No posts</p>
<?php endif; wp_reset_postdata(); ?>

您说过要使用自定义帖子类型并进行分类查询。因此,您可以通过更改$args中的参数来进行调整。

相关问题