列出父页面上的类别中的页面

时间:2014-01-03 18:26:27

标签: php wordpress wordpress-plugin

试图撕掉我的头发。首先,我需要在我已经想到的父页面上显示子页面(带有链接和缩略图)。问题是这些子页面分为“当前”和“过去”两类。所以我找到了一些允许你向页面添加类别的代码(正如你在wordpress中默认情况下不能这样),但是我无法弄清楚如何在下面的代码中添加一些东西,只显示某些类别的页面(我猜一个if和else会工作,它只是查询类别)

以下是我用来显示缩略图和标题的代码:

<?php
$mypages = get_pages( array( 'child_of' => $post->ID, 'sort_column' => 'post_date', 'sort_order' => 'desc' ) );

foreach( $mypages as $page ) {      ?>
            <?php echo get_the_post_thumbnail( $page->ID ); ?>
    <h2><a href="/<?php echo get_page_link( $page->ID ); ?>"><?php echo $page->post_title; ?></a></h2>
<?php
}   
?>

以下是我发现的向页面添加类别的代码:

function myplugin_settings() {  
// Add tag metabox to page
register_taxonomy_for_object_type('post_tag', 'page'); 
// Add category metabox to page
register_taxonomy_for_object_type('category', 'page');  
}
// Add to the admin_init hook of your theme functions.php file 
add_action( 'admin_init', 'myplugin_settings' );

感谢任何可以提供帮助的人

1 个答案:

答案 0 :(得分:0)

尝试按页面ID获取类别,然后使用页面类别

检查您的类别
<?php
$mypages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'post_date', 'sort_order' => 'desc'));

foreach ($mypages as $page) {
    $category = get_the_category($page->ID);
    $categories = array();
    foreach ($category  as $c) {
        $categories[] = $c->cat_name;
    }

    if (in_array("your category name",$categories)){
        ?>
        <?php echo get_the_post_thumbnail($page->ID); ?>
        <h2><a href="/<?php echo get_page_link($page->ID); ?>"><?php echo $page->post_title; ?></a></h2>
    <?php
    }

}
?>

修改

<?php
$mypages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'post_date', 'sort_order' => 'desc'));
?>    

<h1>Category 1</h1>
<?php foreach ($mypages as $page) {
    $category = get_the_category($page->ID);
    $categories = array();
    foreach ($category  as $c) {
        $categories[] = $c->cat_name;
    }    
    if (in_array("Category 1",$categories)){
        ?>
        <?php echo get_the_post_thumbnail($page->ID); ?>
        <h2><a href="/<?php echo get_page_link($page->ID); ?>"><?php echo $page->post_title; ?></a></h2>
    <?php
    }
}
?>
<h1>Category 2</h1>
<?php foreach ($mypages as $page) {
    $category = get_the_category($page->ID);
    $categories = array();
    foreach ($category  as $c) {
        $categories[] = $c->cat_name;
    }    
    if (in_array("Category 2",$categories)){
        ?>
        <?php echo get_the_post_thumbnail($page->ID); ?>
        <h2><a href="/<?php echo get_page_link($page->ID); ?>"><?php echo $page->post_title; ?></a></h2>
    <?php
    }
}
?>