relationships – custom intermediary post title and slug

Toolset Relationships is another powerful feature of Toolset. When it creates a many-to-many relationship, it creates an intermediary CPT. By default the title and slug of the intermediary post are created by “relationship_title: parent_ID – child_ID” and “relationship_slug-parent_ID-child_ID”. For example, if we have the relationship “Writers Books”, the intermediary title would be “Writers Books: 205 – 167” and the slug “writers-books-205-167”.

If for some reason you need to display intermediary posts on front-end, it is possibe to customize intermediary post title and slug by wp_insert_post() hook.

The snippet will build the new title and slug with this structure: “parent_title child_title” and “parent_slug-child_slug” (ex: “Writer1 Book1” and “writer1-book1”).

// Custom intermediary post slug

add_action( 'wp_insert_post', 'hook_for_intermediary_post', 10, 3 );
function hook_for_intermediary_post( $post_id, $post, $update ) {

  // execute only if a new post is being inserted
  if ($update == false) {

    // post-relationship slug
    $relationship_slug = "parent-child";

    // If this is a revision or not the post that we need to target, return.
    if ( (wp_is_post_revision( $post_id )) || ($post->post_type != $relationship_slug) )
      return;

    // default slug of the created post
    $post_existing_slug = $post->post_name;

    // extracting parent and child post IDs from the slug
    $post_existing_slug_arr = explode('-', $post_existing_slug);

    $parent_id = $post_existing_slug_arr[2];
    $child_id = $post_existing_slug_arr[3];

    // getting title and slug of the parent post
    $parent_title = get_the_title($parent_id);
    $parent_slug = get_post_field( 'post_name', $parent_id );

    // getting title and slug of the child post
    $child_title = get_the_title($child_id);
    $child_slug = get_post_field( 'post_name', $child_id );

    $update_post = array(
      'ID'            => $post_id,
      'post_title'    => $parent_title." ".$child_title,
      'post_name'     => $parent_slug."-".$child_slug,
    );

    // Update the post into the database
    wp_update_post( $update_post );

  }
}


wp_insert_post hook reference: https://developer.wordpress.org/reference/hooks/wp_insert_post/
wp_update_post() reference: https://developer.wordpress.org/reference/functions/wp_update_post/

It will works on relationships creation on back-end and on frontend with Toolset Forms.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>