wordpress: how to add hierarchy to posts
Asked Answered
V

9

10

I am creating a web-site on wordpress platform where I want to be able to post my own book texts. So what I want is to have a some kind of hierarchy where I would add a post and then add children to it (chapters). I found this:

register_post_type( 'post', array(
        'labels' => array(
            'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
        ),
        'public'  => true,
        '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
        '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
        'capability_type' => 'post',
        'map_meta_cap' => true,
        'hierarchical' => false,
        'rewrite' => false,
        'query_var' => false,
        'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
    ) );

and tried to make the 'hierarchical"=>true, but there was no effect. Can anyone help?

Verdi answered 25/5, 2012 at 8:19 Comment(0)
I
13

Here is my workaround. This achieves exactly what you want, to be able to set post parents for the builtin post type post. You can achieve this by adding an action to the registred_post_type action hook. Just add this to your theme's functions.php.

add_action('registered_post_type', 'igy2411_make_posts_hierarchical', 10, 2 );

// Runs after each post type is registered
function igy2411_make_posts_hierarchical($post_type, $pto){

    // Return, if not post type posts
    if ($post_type != 'post') return;
    
    // access $wp_post_types global variable
    global $wp_post_types;
    
    // Set post type "post" to be hierarchical
    $wp_post_types['post']->hierarchical = 1;

    // Add page attributes to post backend
    // This adds the box to set up parent and menu order on edit posts.
    add_post_type_support( 'post', 'page-attributes' );

}

There can be dozens of reasons why making posts hierarchical can be helpful. My use case is that the client wanted to structure their (already existing) posts into issues, where child posts are articles of one issue (parent posts).

This is easily achieved by limiting the query to only show posts that have no parents, using.

 'post_parent' => 0,

in your query $args.

Incontrollable answered 26/10, 2016 at 11:21 Comment(4)
nice. you have a extra closing parenthesis, though. Should be: add_action('registered_post_type', 'igy2411_make_posts_hierarchical', 10, 2 );Prue
Doesn't seem to work anymore (WP 5.3). Solution in https://mcmap.net/q/1039948/-wordpress-how-to-add-hierarchy-to-posts worked for me.Erysipeloid
Great solution, except posts do not take the parent slugBulkhead
When using this code on version 5.7.2, the "Parent Post" field does not show. I needed to use this filter developer.wordpress.org/reference/hooks/… and set the 'parent_item_colon' property to 'Parent Post'.Q
A
12

WP 4.9.*+

Workaround above makes it crazy with Friendly URLs.

My solution to add hierarchy to any existing post type using register_post_type_args filter hook:

add_filter('register_post_type_args', 'add_hierarchy_support', 10, 2);

function add_hierarchy_support($args, $post_type){

  if ($post_type === 'post') { // <-- enter desired post type here

    $args['hierarchical'] = true;
    $args['supports'] = array_merge($args['supports'], array('page-attributes'));
  }

  return $args;
}

Re-save wp settings at: /wp-admin/options-permalink.php

Amandaamandi answered 19/3, 2018 at 9:8 Comment(3)
What kind of friendly urls? Because I was noticing I could not get hiearchical URLS as in /parent-post-slug/child-post-slug/ and would just get /child-post-slug/Officious
It works but, why does it change the menu item name from "Post" to "Page"? Now I get two "Page" menu items on the sidebar.Q
@Q Add these $args['labels']['name'] = 'Post'; $args['labels']['singular_name'] = 'Post'; $args['labels']['menu_name'] = 'Post'; before $args['hierarchical'] = true;Kienan
O
7

Update

Due to comments provoking new use-cases and issues, I rewrote this code and I am using it on my own sites [tested in 5.8.2]. I have provided a gist for it. You can include it in your functions.php, or make it into a plugin.

https://gist.github.com/amurrell/00d29a86fc1a773274bf049ef545b29f

🎉 This new update is leveraging SQL (fast!) to resolve the slug and post id to determine the permalink & routing. It produces the exact matching post id, even if you are using the same post_name for different post descendants. It's really fast & reliable!

In the gist, the most interesting function is get_post_from_uri($uri)

  • I built a custom query that will determine the permalink for us and find the exact matching post id.
  • Why a query? There are no wordpress functions to help determine a post's full lineage, without spinning yourself into loops.
  • But the relationships exist in the data!!
  • Therefore, the perfect way to ensure we get good friendly permalink urls is to leverage the power of the database and query language.

👇 Let's see how the query works. This may not be a perfect 1-1 of the code, because I made it dynamic, but the concept is there:

Example:

I have the following posts:

  • climate [547]
  • alliance-for-innovation [1395]
    • climate [1808]
  • procurement [518]
    • city-sales-cycle [1345]
      • climate [1811]

See it in SQL:

mysql> select id, post_name, post_parent from wp_posts where post_type = 'post' and id in (1811, 1808, 1345, 1395, 547, 518);
+------+-------------------------+-------------+
| id   | post_name               | post_parent |
+------+-------------------------+-------------+
|  518 | procurement             |           0 |
|  547 | climate                 |           0 |
| 1345 | city-sales-cycle        |         518 |
| 1395 | alliance-for-innovation |           0 |
| 1808 | climate                 |        1395 |
| 1811 | climate                 |        1345 |
+------+-------------------------+-------------+

Ex URL: alliance-for-innovation/climate

The full query...

mysql> select * from
    -> (select TRIM(BOTH '/' FROM concat(
    ->   IFNULL(p3_slug,''),
    ->   '/',
    ->   IFNULL(p2_slug,''),
    ->   '/',
    ->   p1_slug
    -> )
    -> ) as slug,
    -> id
    -> from (
    -> select d2.*, p3.post_name as p3_slug, p3.post_parent as p3_parent from (
    -> select d1.*, p2.post_name as p2_slug, p2.post_parent as p2_parent from (
    -> select id, post_name as p1_slug, post_parent as p1_parent from wp_posts where post_type = 'post' and post_name = 'climate'
    -> ) as d1
    -> left join wp_posts p2 on p2.id = d1.p1_parent
    -> ) as d2
    -> left join wp_posts p3 on p3.id = d2.p2_parent) as d3
    ->
    -> ) as all_slugs
    -> where slug = 'alliance-for-innovation/climate';
+---------------------------------+------+
| slug                            | id   |
+---------------------------------+------+
| alliance-for-innovation/climate | 1808 |
+---------------------------------+------+
1 row in set (0.01 sec)

I now have both the post ID and the slug, or permalink, I should be using!

It is worth noting I went to the level of p3, which is one extra level than the URL would require (being two parts). This is to prevent something like alliance-for-innovation/climate/something from matching.

How does it work? Break down the query

There's an inside query that looks for the last part of the URL, aka basename. In this case it would be climate.

mysql> select id, post_name as p1_slug, post_parent as p1_parent from wp_posts where post_type = 'post' and post_name = 'climate';
+------+---------+-----------+
| id   | p1_slug | p1_parent |
+------+---------+-----------+
|  547 | climate |         0 |
| 1808 | climate |      1395 |
| 1811 | climate |      1345 |
+------+---------+-----------+

Programmatically, we keep adding abstractions around the query that's directly related to the number of / in the url, so that we can find more information about the post_parent's slug.

mysql> select d1.*, p2.post_name as p2_slug, p2.post_parent as p2_parent from (
    -> select id, post_name as p1_slug, post_parent as p1_parent from wp_posts where post_type = 'post' and post_name = 'climate'
    -> ) as d1
    -> left join wp_posts p2 on p2.id = d1.p1_parent;
+------+---------+-----------+-------------------------+-----------+
| id   | p1_slug | p1_parent | p2_slug                 | p2_parent |
+------+---------+-----------+-------------------------+-----------+
|  547 | climate |         0 | NULL                    |      NULL |
| 1808 | climate |      1395 | alliance-for-innovation |         0 |
| 1811 | climate |      1345 | city-sales-cycle        |       518 |
+------+---------+-----------+-------------------------+-----------+

After we abstracted enough times, we can then select concats as slug like: p1_slug + '/' + p2_slug

mysql> select TRIM(BOTH '/' FROM concat(
    ->   IFNULL(p3_slug,''),
    ->   '/',
    ->   IFNULL(p2_slug,''),
    ->   '/',
    ->   p1_slug
    -> )
    -> ) as slug,
    -> id
    -> from (
    -> select d2.*, p3.post_name as p3_slug, p3.post_parent as p3_parent from (
    -> select d1.*, p2.post_name as p2_slug, p2.post_parent as p2_parent from (
    -> select id, post_name as p1_slug, post_parent as p1_parent from wp_posts where post_type = 'post' and post_name = 'climate'
    -> ) as d1
    -> left join wp_posts p2 on p2.id = d1.p1_parent
    -> ) as d2
    -> left join wp_posts p3 on p3.id = d2.p2_parent) as d3
    ->
    -> ;
+--------------------------------------+------+
| slug                                 | id   |
+--------------------------------------+------+
| climate                              |  547 |
| alliance-for-innovation/climate      | 1808 |
| procurement/city-sales-cycle/climate | 1811 |
+--------------------------------------+------+

The last step is to add a where for the original url: alliance-for-innovation/climate. And that's what you see in the full query example we first examined!

Let's see how the others go:

# climate

+---------+-----+
| slug    | id  |
+---------+-----+
| climate | 547 |
+---------+-----+
# procurement/city-sales-cycle/climate

+--------------------------------------+------+
| slug                                 | id   |
+--------------------------------------+------+
| procurement/city-sales-cycle/climate | 1811 |
+--------------------------------------+------+

Another thing that I like about this update is that I remembered to:

Escape the climate, or basename of the URL that we use in the query, because this is technically user-inputted (via url)

$wpdb->_real_escape($basename));

So how is this query-building function dynamic?

We use PHP arrays, loops, etc to build a string that will be the query so that we do not have to use PHP for logic about the data itself.

This is a snippet showing the dynamic abstractions - eg. how many p1_slug, p2_slug, p3_slug to grab.

// We will do 1 more depth level than we need to confirm the slug would not lazy match
  // This for loop builds inside out.
  for ($c = 1; $c < $depth + 2; $c++) {
    $d = $c;
    $p = $c + 1;

    $pre = "select d${d}.*, p${p}.post_name as p${p}_slug, p${p}.post_parent as p${p}_parent from (";
    $suf = ") as d${d} left join $wpdb->posts p${p} on p${p}.id = d${d}.p${c}_parent";

    $sql = $pre . $sql . $suf;

    $concats[] = sprintf("IFNULL(p${p}_slug,'')");
  }

Previous Answer:

I came here looking to achieve:

  1. Adding page attributes to post_type posts to add parent posts
  2. Being able to add a page template to post_type posts
  3. Being able to get hierarchical permalink structure on post_type posts

I was able to use the accepted answer to accomplish 1 & 2, but not 3.

Note: to fully get 2 to work, you need to specify the post_type in the template comments of your page template like this:

<?php
/*
Template Name: Your Post Template Name
Template Post Type: post
*/

For 3, I found a plugin that ruined my post_type pages, and it was a lot of pretty awful, unmaintained code.

So I wrote a solution to accomplish all this, borrowing from this answer:

(Tested with 4.9.8)

<?php

add_action('registered_post_type', 'make_posts_hierarchical', 10, 2 );

// Runs after each post type is registered
function make_posts_hierarchical($post_type, $pto){

    // Return, if not post type posts
    if ($post_type != 'post') return;

    // access $wp_post_types global variable
    global $wp_post_types;

    // Set post type "post" to be hierarchical
    $wp_post_types['post']->hierarchical = 1;

    // Add page attributes to post backend
    // This adds the box to set up parent and menu order on edit posts.
    add_post_type_support( 'post', 'page-attributes' );

}

/**
 * Get parent post slug
 * 
 * Helpful function to get the post name of a posts parent
 */
function get_parent_post_slug($post) {
  if (!is_object($post) || !$post->post_parent) {
    return false;
  }

  return get_post($post->post_parent)->post_name;
}

/**
 * 
 * Edit View of Permalink
 * 
 * This affects editing permalinks, and $permalink is an array [template, replacement]
 * where replacement is the post_name and template has %postname% in it.
 * 
 **/
add_filter('get_sample_permalink', function($permalink, $post_id, $title, $name, $post) {
  if ($post->post_type != 'post' || !$post->post_parent) {
    return $permalink;
  }

  // Deconstruct the permalink parts
  $template_permalink = current($permalink);
  $replacement_permalink = next($permalink);

  // Find string
  $postname_string = '/%postname%/';

  // Get parent post
  $parent_slug = get_parent_post_slug($post);

  $altered_template_with_parent_slug = '/' . $parent_slug . $postname_string;
  $new_template = str_replace($postname_string, $altered_template_with_parent_slug, $template_permalink);

  $new_permalink = [$new_template, $replacement_permalink];

  return $new_permalink;
}, 99, 5);

/**
 * Alter the link to the post
 * 
 * This affects get_permalink, the_permalink etc. 
 * This will be the target of the edit permalink link too.
 * 
 * Note: only fires on "post" post types.
 */
add_filter('post_link', function($post_link, $post, $leavename){

  if ($post->post_type != 'post' || !$post->post_parent) {
    return $post_link;
  }
  
  $parent_slug = get_parent_post_slug($post);
  $new_post_link = str_replace($post->post_name, $parent_slug . '/' . $post->post_name, $post_link);

  return $new_post_link;
}, 99, 3);

/**
 * Before getting posts
 * 
 * Has to do with routing... adjusts the main query settings
 * 
 */
add_action('pre_get_posts', function($query){
  global $wpdb, $wp_query;

  $original_query = $query;
  $uri = $_SERVER['REQUEST_URI'];

  // Do not do this post check all the time
  if ( $query->is_main_query() && !is_admin()) {

    // get the post_name
    $basename = basename($uri);
    // find out if we have a post that matches this post_name
    $test_query = sprintf("select * from $wpdb->posts where post_type = '%s' and post_name = '%s';", 'post', $basename);
    $result = $wpdb->get_results($test_query);

    // if no match, return default query, or if there's no parent post, this is not necessary
    if (!($post = current($result)) || !$post->post_parent) {
      return $original_query;
    }

    // get the parent slug
    $parent_slug = get_parent_post_slug($post);
    // concat the parent slug with the post_name to get most of the url
    $hierarchal_slug = $parent_slug . '/' . $post->post_name;

    // if the concat of parent-slug/post-name is not in the uri, this is not the right post.
    if (!stristr($uri, $hierarchal_slug)) {
      return $original_query;
    }

    // pretty high confidence that we need to override the query.
    $query->query_vars['post_type'] = ['post'];
    $query->is_home     = false;
    $query->is_attachment = false;
    $query->is_page     = true;  
    $query->is_single   = true; 
    $query->queried_object_id = $post->ID;  
    $query->set('page_id', $post->ID);

    return $query;
  }


}, 1);

You can save this to a file custom-posts-hierarchy.php and include it in your functions.php file in your theme, or you can add to the top:

/*
Plugin Name: Custom Posts Hierarchy
Plugin URI:
Description: Add page attributes to posts and support hiearchichal
Author: Angela Murrell
Version:
Author URI: 
*/

And drop it into your plugins folder. Good luck!

Officious answered 9/1, 2019 at 12:30 Comment(11)
Parent slug not working for me, just blank in permalink, so you end up with //post-slug - maybe because my parent post is in Draft. the parent post object does not have a post_name value. Weird.Bulkhead
Confirmed. Published post, then re-saved as draft, post slug working now.Bulkhead
Yes, the function to get the post parent slug is looking for a post_name so you need to have that stored on your parent post: return get_post($post->post_parent)->post_name; If publishing helps you accomplish this, then do so!Officious
@Officious This allows to create a post /hello and another post /parent1/hello (this one has parent1 as parent), which is very useful in many cases! But, problem, when accessing /parent1/hello, the browser changes the URL to /hello and you get the wrong post. Do you have an idea about how to modify this? I started a bounty for this.Deimos
@Deimos 1- Do you want this behavior for the wordpress default posts? Or for a custom post type? 2- Could you provide me with a screenshot of your permalink settings? I'd like to see how you've setup your permalinks. I'll work on it If you could elaborate more on the specifics you're looking for!Corpora
@Deimos What do you mean the browser changes the URL? My bet is wordpress trying auto-detect your routing and finding the closest page to it. can you confirm that you have selected the page templates for both pages, they are published, you have the code from my answer implemented?Officious
@Corpora For default posts. Permalink settings are set to /%postname%/. This situation happens if you create a post named hello without parent, and then another post named hello with parent post parent1. (Or maybe the reverse creation date, I don't remember).Deimos
@Officious This situation happens if you create a post named hello without parent, and then another post named hello with parent post parent1 (URL /parent1/hello/), or maybe the reverse creation date, I don't remember. Since the two posts have the same slug, the routing chooses one or the other, based on the first creation date.Deimos
@Deimos Okay I understand what you mean - I am going to try to figure out if I can reproduce that on a working instance I have.Officious
@Deimos I did figure something out that's awesome. I adjusted the query (it's a complex query) to find the exact matching post id that could represent the URI. I just need a few more days to actually update this answer with it as an option.Officious
@Deimos I updated this answer with my newest solution, that I am using on my own stuff with no issue. Worked on 4.9 - 5.8.2Officious
B
2

Posts in Wordpress are supposed to be typical chronological Blog Posts. Pages are made for static content, they can be organised in a hierarchical structure out of the box.

For any Page, you can select a parent page. This way, you can create nested hierarchies with multiple children. Sounds like what you need.

Check the Wordpress Documentation for details.

If you have a deep, complicated tree structure, a plugin might help you manage it, like Wordpress Page Tree. It provides a better interface than the default Wordpress Page listing.

Blaise answered 25/5, 2012 at 9:3 Comment(2)
The thing is that I also want users to be able to post. And I can't provide them ability to add pages due to security reasons :( I also found a plugin for this, but it does not allow adding categories: "Generic Parent Child Custom Post Type". Maybe there is any way to add categories to the plugin. Do you know how I can do it?Verdi
That's a completely different question, then. Why would you let a user add Posts (or event a custom post type) but not Pages? Maybe you should open another question describing what kind of user interaction you are trying to achieve.Blaise
S
1

Using a plugins like CPT UI, you can create a custom post type and set it to have hierarchical tree.

Then just check that the post type page-attribute is set for this custom post type and voile, your posts now have hierarchical states.

https://wordpress.org/plugins/custom-post-type-ui/

Soloma answered 6/5, 2014 at 11:46 Comment(0)
L
0

best solution is to create custom taxonomy [1]: http://codex.wordpress.org/Function_Reference/register_taxonomy and create main slug - books or something else.

Lepanto answered 25/5, 2012 at 9:8 Comment(0)
D
0

There exists plugin, which creates hierarchy for post:

https://wordpress.org/plugins/add-hierarchy-parent-to-post/

Dorladorlisa answered 7/2, 2017 at 8:28 Comment(1)
I tried using this plugin - because I was in a rush. But It has a bunch of mistakes in it and rough code (lots of commented out garbage) and forces the download of some generic configuration file that the parent plugin company uses in all their plugins. Seemed a like a bunch of bloatware.... It also ruined pages from showing for me after implementing. I do not recommend this plugin.Officious
L
0

Isn't this a better option?

register_post_type( 'MYPOSTTYPE',
    array(
        'labels' => array(
            'name' => __( 'MYPOSTTYPE' ),
            'singular_name' => __( 'MYPOSTTYPE' )
        ),
        'supports' => array('title', 'editor', 'page-attributes'),
        'public' => true,
        'has_archive' => true,
        'hierarchical' => true,
        'rewrite' => array('slug' => 'MYPOSTTYPE'),
    )
);

I have added:

'hierarchical' => true,

and it works.

Lathrop answered 1/6, 2018 at 7:55 Comment(2)
Also, to make it work you have to have posted something allready! And your 'supports' => array was missing 'page-attributes'.Lathrop
The reason I hate using custom post types is it forces a whole tier to the URL /my-post-type/ and this is actually pretty bad for SEO purposes if you plant on silo-ing a bunch of content here - like articles that could have topics. Creating a new post type for each topic area is annoying. I suppose you could use categories on posts instead but I don't like having to deal with categories within the wordpress database - the taxonomies involve a lot of joins.Officious
U
0

I was also considering to add hierarchy to posts and I read through this topic. My conclusion is that (in my opinion) it is better to avoid adding hierarchy to posts. Post and page hierarchy is such a core concept of Wordpress, and all kinds of issues with SEO and compatibility with plugins (and Wordpress core) can come up when touching this. Instead of implementing a complicated technical solution, and having to hope that it remains compatible with future Wordpress and plugin updates, it seems better to use categories and subcategories for hierarchy of posts. And if that doesn't provide sufficient flexibility, use pages instead of posts because pages also come with support for hierarchy out of the box (as previously mentioned by others).

There may be situations where it looks like post categories or pages both can't solve your hierarchy problem but I'd still argue that you should consider whether you want to complicate things for yourself by implementing some form of customized post hierarchy solution, and all the future problems that can come from it.

While it is tempting to come up with a technical solution for a problem, sometimes the best answer is to not do something at all and use a different approach altogether. I strongly believe that is the case here.

Uturn answered 18/1, 2023 at 10:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.