WordPress PHP 按类别名称查询


wordpress php query by category name

我想为单独的类别帖子做单独的博客页面。我能够找到的是按类别编号运行查询,但这对我来说不够动态,因为我想对页面标题运行查询,即 = 类别名称。

基本上在"事件"页面上,我想显示名为"事件"(类别名称==页面标题)的类别下的博客文章,依此类推。

关于如何实现这一目标的任何见解都将很棒。我试图做但失败的是:

<?php query_posts('category_name='.get_the_title()); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <div>
        <h1><?php the_title(); ?></h1>
        <p><?php the_content(); ?></p>
    </div>
<?php endwhile; else: ?>no match<?php endif; ?>

感谢您转发任何见解,链接或通知。

首先,永远不要使用query_posts。 它破坏了主查询,重新运行了减慢页面速度的查询,错误地设置了插件使用的重要功能,get_queried_object()等功能,并且弄乱了分页。

如果需要运行自定义查询,请使用 WP_Query

为了解决您的原始问题,默认类别参数不使用类别名称,仅使用蛞蝓和 ID。数据域是可控的,因此您可能希望将 slug 与 category_name 参数一起使用。

如果确实需要传递类别名称,则应使用接受传递给terms参数的名称的tax_query

您可以使用参数传递以下内容

'tax_query' => array(
    array(
        'taxonomy' => 'category',
        'field' => 'name',
        'terms' => 'name of your category',
        'include_children' => false,
    ) ,
);
您可以使用

get_post函数来做到这一点。

这样做:

<?php
    $args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );
    $myposts = get_posts( $args );
    foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    <div>
        <h1><?php the_title(); ?></h1>
        <p><?php the_content(); ?></p>
    </div>
    <?php endforeach; 
    wp_reset_postdata();
?>

如果您需要进一步的帮助,请告诉我。