Select pages by category

时间:2016-09-16 作者:brandozz

是否可以使用get\\u pages功能根据类别选择页面?我已经将猫添加到我的页面分类中。下面的代码只是拉取我的所有页面,忽略$args:

<?php

    echo \'<ul>\';
    $args = array(
        \'category\' => 25
    ); 
    $pages = get_pages($args);
    foreach ( $pages as $page ) {
        $option = \'<li><a href="\' . get_page_link( $page->ID ) . \'">\';
        $option .= $page->post_title;
        $option .= \'</a></li>\';
        echo $option;
     }
    echo \'</ul>\';

?>

1 个回复
SO网友:brandozz

多亏了下面的帖子,我才能够解决这个问题How to Add Categories to Pages in Wordpress. 我需要修改WP\\u查询,以便在显示帖子列表时包含页面。以下是解决方案:

在我的模板文件中:

$args = array(
        \'category\'  => 25,
        \'orderby\'   => \'date\',
        \'order\'     => \'ASC\'
    ); 
    $pages = get_posts($args);
    foreach ( $pages as $page ) {
        setup_postdata($page);
        $mykey_values = get_post_custom_values( \'webinar_link\', $page->ID );
        echo \'<div class="media webinar webinar-upcoming">\';
        echo \'<a class="pull-left" href="\' . get_page_link($page->ID) . \'" title="\' . $page->post_title . \'">\';
        if ( has_post_thumbnail( $page->ID ) ) {
            $image_array = wp_get_attachment_image_src( get_post_thumbnail_id( $page->ID ), \'optional-size\' );
            $image = $image_array[0];
        }
        echo \'<img class="media-object responsive-image" src="\' . $image . \'"></a>\';
        echo \'<div class="media-body extra-bottom-pad">\';
        echo \'<h2><a href="\' . get_page_link( $page->ID ) . \'">\' . $page->post_title . \'</a></h2>\';
        the_content(\'\');
        echo \'<a class="pull-left vistex-button-sm more-link" href="\' . get_page_link($page->ID) . \'" title="\' . $page->post_title . \'">Learn More</a>\';
        foreach ($mykey_values as $key => $value) {
            echo \'<p><a class="vistex-button-sm more-link" style="margin-left: 10px;" target="_blank" href="\' . $value . \'">Register Now</a></p>\'; 
        }
        echo \'</div>\';
        echo \'</div>\';
在我的函数文件中:

/* add categories to pages */
function cats_pages() {  
    // Add category metabox to page
    register_taxonomy_for_object_type(\'category\', \'page\');  
}
add_action( \'init\', \'cats_pages\' );

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

if (!is_admin() ) {
    add_action( \'pre_get_posts\', \'category_and_tag_archives\' );
}

function category_and_tag_archives( $wp_query ) {
    $my_post_array = array(\'post\',\'page\');

    if ( $wp_query->get( \'category_name\' ) || $wp_query->get( \'cat\' ) )
     $wp_query->set( \'post_type\', $my_post_array );

     if ( $wp_query->get( \'tag\' ) )
     $wp_query->set( \'post_type\', $my_post_array );
这确实将我的网站中的每一个页面都添加到了博客中,因此您需要选择要列出的类别。

在我的索引中。php文件:

<?php $query = new WP_Query(\'cat=-7,-19,17,18,9,15,16,1\'); ?>