Aleš Sýkora / December 6, 2023 / 0 comments

Get a grandparent post ID from a shortcode with Toolset

Post summary: This simple shortcode will allow you to get that grandparent post ID without the need for additional Content Templates or Views.

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

Fuel my passion for writing with a beer🍺

Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻

0 comments

Share Your Thoughts