列出Wordpress中某个类别的所有页面

时间:2018-03-14 08:02:30

标签: php wordpress

我正处于一场小危机中。我需要你的帮助!我做了几个小时的研究,但这是我的最后一招。切入故事,我试图列出所有的页面'来自Wordpress中的活动类别。

以下是我迄今为止所做的步骤。我可以通过在 functions.php 文件中添加以下代码来为我的网页启用类别:

function jh_cats() {  
    register_taxonomy_for_object_type('post_tag', 'page'); 
    register_taxonomy_for_object_type('category', 'page');
}
add_action( 'init', 'jh_cats' );

接下来,我需要做到这一点,以便网站有类别&子类别。子类别仅显示在父类别页面上。我已将以下内容添加到 category.php 文件中,以获取所有子类别的列表。

<?php

$categories = get_categories( array(
    'orderby' => 'name',
    'parent'  => $cat,
    'hide_empty' => FALSE
) );
if ($categories)
{
    foreach ( $categories as $category ) 
    {?>         
        <li><a href="<?php echo $category->slug ?>"><?php echo $category->name ?></a></li>                         
<?php 
    }
} ?>

现在,当您访问特定的子类别时(考虑不会将任何内容分配给主要类别),我需要能够列出分配该子类别的所有页面。

接下来我该怎么办?我的 index.php 中有这个,但这只列出了所有页面。无论您是否属于特定类别,都可以。

<ul>
    <?php
    global $post;

    $myposts = get_posts( array(
        'post_type' => 'page',
        'posts_per_page' => 5
    ) );

    if ( $myposts ) {
        foreach ( $myposts as $post ) : 
            setup_postdata( $post ); ?>
            <li>
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                <?php the_content(); ?>
            </li>
        <?php
        endforeach;
        wp_reset_postdata();
    }
    ?>
</ul>

希望你能帮忙!谢谢。 :) 在此处回复其他人的回复/代码,以帮助我解决一些早期问题。

2 个答案:

答案 0 :(得分:0)

你有没有尝试过这样的东西,对于你的index.php代码:

$myposts = get_posts( array(
    'post_type' => 'page',
    'taxonomy' => 'category'
) );

另外,我会尝试避免“get_categories”,最好尽可能尝试使用“get_terms”函数。

答案 1 :(得分:0)

在您希望过滤帖子的页面上,您可以尝试使用from re import sub name = ['Nora', 'John', 'Jack', 'Jessica'] html = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Names</title> </head> <body> <ul> <li>Mother: <%= name[0] %></li> <li>Father: <%= name[1] %></li> <li>Son: <%= name[2] %></li> <li>Daughter: <%= name[3] %></li> </ul> </body> </html> """ html = sub(r"<%=\s*(\S+)\s*%>", lambda l: eval(l.group(1)), html) print(html) 返回数组。然后使用foreach或者只获得第一项:

$cat = get_the_category($post->id);

然后更新WP查询以显示使用该类别的所有帖子。

按ID:

$cat_id = $cat[0]->cat_ID;

按名称:

$query = new WP_Query( array( 
    'post_type' => 'page',
    'cat' => $cat_id
) );

来源:https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

相关问题