Get a grandparent post ID from a shortcode

Author: Aleš Sýkora, 1. 7. 2019

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"]

Snippet created by: Beda Schmid

for Toolset, Toolset Types, Toolset Views