Skip to content

Instantly share code, notes, and snippets.

@MickeyKay
Created January 8, 2015 19:41
Show Gist options
  • Save MickeyKay/331604b00acb5a3319b3 to your computer and use it in GitHub Desktop.
Save MickeyKay/331604b00acb5a3319b3 to your computer and use it in GitHub Desktop.
Custom Simple Section Navigation for posts that don't have a parent
<?php
add_shortcode( 'ssn', 'esw_custom_ssn' );
/**
* Emulate Simple Section Nav for a specific parent post/page.
*
* Example: [ssn ancestor="ancestor_id" parent="parent_id" depth="depth"]
*
* @since 1.0.0
*
* @param array $atts Shortcode atts.
*
* @return string Output HTML.
*/
function esw_custom_ssn( $atts ) {
global $post;
if ( ! isset( $atts['parent'] ) ) {
$atts['parent'] = '';
}
/**
* Global variable to hold shortcode parent value
*
* Fix this properly with OOP practice:
* http://wordpress.stackexchange.com/questions/45901/passing-a-parameter-to-filter-and-action-functions
*/
global $esw_ssn_parent_ids;
$esw_ssn_parent_ids[] = $atts['parent'];
/** Get shortcode parameters */
extract( shortcode_atts( array(
'ancestor' => '',
'parent' => '',
'depth' => '1',
'show_all' => false,
'exclude' => '',
'hide_on_excluded' => true,
'show_on_home' => false,
'show_empty' => false,
'sort_by' => 'menu_order',
'a_heading' => false,
'before_widget' => '<div class="custom-ssn simple-section-nav" data-parent="' . $atts['parent'] . '">',
'after_widget'=>'</div>',
'before_title'=>'<h4 class="widget-title">',
'after_title'=>'</h4>',
), $atts ) );
// Add class for current parent
add_filter( 'page_css_class', 'esw_apply_custom_ssn_classes', 10, 6 );
// Only if $ancestor is set
if ( ! empty( $ancestor ) ) {
$content = $before_widget . $before_title . get_the_title( $ancestor ) . $after_title . '<ul>';
$content .= wp_list_pages( array(
'child_of' => $ancestor,
'title_li' => '',
'depth' => $depth,
'sort_column' => $sort_by,
'exclude' => $exclude,
'echo' => false,
)
);
$content .= '</ul>' . $after_widget;
return $content;
}
}
/**
* Add 'current' class to
*
* @since 1.0.0
*
* @see wp_list_pages()
*
* @param array $css_class An array of CSS classes to be applied
* to each list item.
* @param WP_Post $page Page data object.
* @param int $depth Depth of page, used for padding.
* @param array $args An array of arguments.
* @param int $current_page ID of the current page.
*
* @return string Updated CSS classes.
*/
function esw_apply_custom_ssn_classes( $css_class, $page, $depth, $args, $current_page ) {
global $esw_ssn_parent_ids;
// Get all ancestors
$ancestors = get_post_ancestors( $page->ID );
/**
* Add 'current' class if:
* - Page ID is in parent array
* - Page ancestor array matches ancestor array
*/
if ( in_array( $page->ID, $esw_ssn_parent_ids ) ||
array_intersect( $ancestors, $esw_ssn_parent_ids )
) {
$css_class[] = 'current_page_parent';
}
return $css_class;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment