How to "group" (categorize) the Pages together?

I have a lot of Pages which can be (need to be) grouped under a number of different Categories. ** Then the more important thing is, i need to control those pages (of different groups) programatically via functions.php.

Lets say, i would have:

  • Page A (Categorized as: Fruits)
  • Page B (Categorized as: Vehicles)
  • Page C (Categorized as: Vehicles)
  • Page D (Categorized as: Fruits)
  • Page E (Categorized as: Technology)

Then from functions.php, there would be some logics, like:

  • If Page is under Fruits Category, then echo "This is related to Fruits.";.
  • If Page is under Vehicles Category, then echo "This is related to Vehicles.";.
  • If Page is under Technology Category, then echo "This is related to Technologies.";.

I dont know this is about Taxonomy or Tagging or Custom Field or something. But:

  • What is the ideal way to do it please? (Especially to be able to control from backend coding.)

And again please let me repeat, "Pages". (Not about Posts or any other)

Topic tags taxonomy categories pages custom-field Wordpress

Category Web


  1. First thing you need to do is to enable categories for pages, quite simple:

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

Note that in WordPress, categories are shared between different post types

  1. To register the categories in advance:
    $wp_insert_category(array(
        'cat_name' => 'Fruit',
        'category_description' => 'My Fruit posts',
        'category_nicename' => 'Fruit'
    ));
    
  2. You can add categories to posts programmatically:
    wp_set_post_categories($post->ID, get_cat_ID( 'Fruit' ));
    
  3. When displaying the page (named in Wordpress $post):
    if ($post->post_type == 'page'){
        if (has_category( 'Fruits', $post)){
            echo "This is related to Fruits.";
        }
    }
    

You can use categories with pages by registering the category taxonomy for the page object type:

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

If you want to use a separate taxonomy for this, you can register your own taxonomy for pages.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.