Skip to content

Instantly share code, notes, and snippets.

@NicolasLRD
Created April 3, 2019 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NicolasLRD/77906c2ad7d6d3613e3b2a1d6564acc7 to your computer and use it in GitHub Desktop.
Save NicolasLRD/77906c2ad7d6d3613e3b2a1d6564acc7 to your computer and use it in GitHub Desktop.
Wordpress Widget : List pages of parent page
<?php
function template_register_widget() {
register_widget( 'my_widget' );
}
add_action( 'widgets_init', 'template_register_widget' );
class my_widget extends WP_Widget {
function __construct() {
parent::__construct(
// widget ID
'my_widget',
// widget name
__('List pages of parent page', ' my_widget_domain'),
// widget description
array( 'description' => __( 'List pages of same level', 'my_widget_domain' ), )
);
}
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
echo $args['before_widget'];
//if title is present
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
//output
global $post;
$parentPage = $post->post_parent;
$currentSlug = $post->post_name;
$args = array(
'post_type' => 'page',
'posts_per_page' => -1,
'post_parent' => $parentPage,
'order' => 'ASC',
'orderby' => 'menu_order'
);
$parent = new WP_Query( $args );
if ( $parent->have_posts() ) : ?>
<?php while ( $parent->have_posts() ) : $parent->the_post(); ?>
<?php $postSlug = $post->post_name;
if($currentSlug == $postSlug){
echo'<div id="parent-'. get_the_ID() .'" class="level-page current-menu">';
}
else{
echo'<div id="parent-'. get_the_ID() .'" class="level-page">';
} ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</div>
<?php endwhile; ?>
<?php endif; wp_reset_postdata();
//echo __( 'Hello, World from Hostinger.com', 'my_widget_domain' );
echo $args['after_widget'];
}
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) )
$title = $instance[ 'title' ];
else
$title = __( 'Default Title', 'my_widget_domain' );
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment