Displaying static page content in a widgetizable zone without a plugin

Pierre-Yves
Veteran
Just Getting Started

Member    Likes (0)

A simple function to display a static page content in a widgetizable zone. Nothing fantastic but if it could help someone.

// Display static page content in a wigetizable zone
class AfficherUnePage extends WP_Widget {
//Constructor
function AfficherUnePage()
{
parent::WP_Widget(false, $name = 'AfficherUnePage', array('name' => 'Afficher une page', 'description' => 'Afficher le contenu dune page dans une zone widgetisable'));
}
//widget display
function widget($args, $instance)
{
extract($args);
$title = apply_filters('widget_title', $instance['title']);
$no_post = $instance['no_post'];
$page_data = get_page($no_post);
echo $before_widget;
echo '<h3>'. $page_data->post_title .'</h3>';
echo apply_filters('the_content', $page_data->post_content);
echo $after_widget;
}
//Widget update
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['no_post'] = $new_instance['no_post'];
return $instance;
}
//Widget option in back office
function form($instance)
{
$title = esc_attr($instance['title']);
$no_post = esc_attr($instance['no_post']);
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">
<?php echo 'Titre:'; ?>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('no_post'); ?>">
<?php echo 'ID de la page:'; ?>
<input class="widefat" id="<?php echo $this->get_field_id('no_post'); ?>" name="<?php echo $this->get_field_name('no_post'); ?>" type="text" value="<?php echo $no_post; ?>" />
</label>
</p>
<?php

}
}
function dfr_register_widget() {
register_widget( 'AfficherUnePage' );
}
add_action('widgets_init', 'dfr_register_widget');

Usage :

Copy the code in the functions.php of your theme (or child theme). A new widget will automatically appear in the widget section. Drag and drop in a widget zone.
Type in the title and the page id. Adjust css according your wishes.
Enjoy it !

Douarnenez, France