ttmt
ttmt

Reputation: 4984

Wordpress get_pages based on page category

I need to get_pages or get an array of pages in WP based on it 's category

I know WP doesn't come with categories on pages but I'm using this in the functions.php to get categories on the pages.

    add_action('admin_init', 'reg_tax');

    function reg_tax() {
        register_taxonomy_for_object_type('category', 'page');
        add_post_type_support('page', 'category');
    }

Now I need to use these categories in get_pages or WP_Query to get in the pages with a category.

     <div class="productNav">

                <ul>

                <?php

                $product_page_args = array(

                    'post_type' => 'page',
                    'order' => 'ASC',
                    'orderby' => 'menu_order',
                    'child_of' => $post->ID,
                    'category_name' => 'pillar-product'
                );

                //$product_pages = get_pages($product_page_args);

                $product_pages = new WP_Query($product_page_args);



                foreach ($product_pages as $product_page){  

                ?>

                    <li><?php echo $product_page->post_title; ?></li>    

                <?php
                }
                ?>

                </ul>

            </div>

Upvotes: 3

Views: 8025

Answers (2)

James
James

Reputation: 186

Respectfully this answer does NOT work anymore in 2021. This is an obsolete answer and includes all of the pages. Please use the other answer.

Try this: (won't work on wordpress 5.8)

$product_page_args = array(

                'post_type' => 'page',
                'order' => 'ASC',
                'orderby' => 'menu_order',
                'child_of' => $post->ID,
                'taxonomy' => 'category',
                        'field' => 'slug',
                        'term' => 'pillar-product'
            );

Upvotes: 7

Ruvee
Ruvee

Reputation: 9097

The accepted answer for this question won't work anymore and includes all of the pages because 'taxonomy', 'field' and 'term' must be inside an array which resides inside 'tax_query' array, for this query to work.

For more comprehensive answer on how to query wordpress pages based on specific category see the following link:

How to query pages based on specific categories

Here's the correct answer for this question, fully tested on wordpress 5.8.

$product_page_args = array(
  'post_type' => 'page',
  'order' => 'ASC',
  'orderby' => 'menu_order',
  'child_of' => $post->ID,
  'tax_query' => array(
    array(
      'taxonomy' => 'category',
      'field'    => 'slug',
      'terms'    => array('pillar-product'),
    )
  )
);

Upvotes: 1

Related Questions