Get a grandparent post ID from a shortcode

Sometimes you want to access a grandparent post ID in the context of a child post. The Toolset method involves nested Content Templates or Views. This simple shortcode will allow you to get that grandparent post ID without the need for additional Content Templates or Views, so it’s useful in conditionals. Add the following code to a new snippet in Toolset > Settings > Custom Code, or add it to your child theme’s functions.php file:

function get_grandparent_id_func( $atts )
{
  $a = shortcode_atts( array(
      'postid' => 0,
      'parentrel' => '',
      'grandparentrel' => ''
  ), $atts );

  $parent = toolset_get_related_post( $a['postid'], $a['parentrel']);
  $grandparent = toolset_get_related_post( $parent, $a['grandparentrel']);

  return $grandparent;
}
add_shortcode( 'get-grandparent-id', 'get_grandparent_id_func' );

To use the shortcode you’ll pass in 3 parameters: the child post ID, the parent relationship slug, and the grandparent relationship slug.

Grandparent post ID: [get-grandparent-id postid="[wpv-post-id]" parentrel="your-parent-relationship-slug" grandparentrel="your-grandparent-relationship-slug"]

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments