Skip to content

Instantly share code, notes, and snippets.

@brettkelly
Created January 5, 2023 04:27
Show Gist options
  • Save brettkelly/ef952a9e0e58e485b7f3af384e32f148 to your computer and use it in GitHub Desktop.
Save brettkelly/ef952a9e0e58e485b7f3af384e32f148 to your computer and use it in GitHub Desktop.
An example of a WordPress shortcode that takes parameters
<?php
/*
Collect and display a sorted, unordered list element containing all children of the current post
Supported attributes:
`remove` = this string will be removed in the resulting links
`exclude` = posts whose title contains one of these comma-separated strings will be omitted
TODO: fix both params to be pipe-delimited because flexibility
*/
function foo_get_child_pages($atts = [], $content = null, $tag = '')
{
global $post;
$children = get_posts(array(
'post_parent' => $post->ID,
'post_status' => 'publish',
'post_type' => 'page',
'orderby' => 'menu_order',
'numberposts' => -1
));
if ($children) {
$atts = array_change_key_case((array)$atts, CASE_LOWER);
$ourattrs = shortcode_atts(
array('remove' => '', 'exclude' => ''),
$atts,
$tag
);
$excludes = explode(',', $ourattrs['exclude']);
$outp = '<ul class="academy-module-menu">';
foreach ($children as $child) {
if (!empty($excludes)) {
$skip = false;
foreach ($excludes as $exclude) {
if (stristr($child->post_title, $exclude)) {
$skip = true;
}
}
if ($skip) {
continue;
}
}
$title = str_replace($ourattrs['remove'], '', $child->post_title);
$outp .= '<li><a href="' . get_the_permalink($child->ID) . '">' . $title . '</a></li>';
}
$outp .= '<ul>';
return $outp;
} else {
return;
}
}
add_shortcode('foo_generate_inline_menu', 'foo_get_child_pages');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment