Skip to content

Instantly share code, notes, and snippets.

@michaeldyrynda
Created August 5, 2014 03:56
Show Gist options
  • Save michaeldyrynda/682f6f67e91dc0b96473 to your computer and use it in GitHub Desktop.
Save michaeldyrynda/682f6f67e91dc0b96473 to your computer and use it in GitHub Desktop.
Shortcode method to generate an unordered HTML list of either child or sibling links, relative to the current post
<?php
/**
* Render an unordered HTML list of related page links
*
* @return string
*/
function renderRelatedLinks($atts)
{
global $post, $wpdb;
extract(shortcode_atts(
array(
'type' => 'child',
),
$atts
));
if ( ! isset($post->ID) ) {
return null;
}
switch ($type) {
case 'child':
$parent = $post->ID;
break;
case 'sibling':
$parent = $post->post_parent;
break;
default:
$parent = null;
break;
}
if ( is_null($parent) ) {
return null;
}
$sql = sprintf(
' SELECT `ID`,
`post_title`,
`menu_order`
FROM `%s`
WHERE `post_type` = "page"
AND `post_parent` = %d
ORDER BY `menu_order`, `post_title`',
$wpdb->posts,
$parent
);
if ( $siblings = $wpdb->get_results($sql) ) {
$html = null;
foreach ($siblings as $sibling) {
$current = ($sibling->ID == $post->ID);
$html .= sprintf(
'<li class="%s"><a href="%s">%s</a></li>',
$current ? 'current' : null,
get_permalink($sibling->ID),
$sibling->post_title
);
}
if ( ! is_null($html) ) {
$html = sprintf('<ul>%s</ul>', $html);
}
return $html;
}
return null;
}
add_shortcode('sc_related_links', 'renderRelatedLinks');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment