Skip to content

Instantly share code, notes, and snippets.

@dragipostolovski
Last active March 22, 2021 10:29
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 dragipostolovski/7d82a9da334dfc1f540d9e92df667c93 to your computer and use it in GitHub Desktop.
Save dragipostolovski/7d82a9da334dfc1f540d9e92df667c93 to your computer and use it in GitHub Desktop.
How to Create a WordPress Custom Widget
<?php
class PE_Random_Post extends WP_Widget {
public function __construct() {
// actual widget processes
parent::__construct(
'pe_random_post', // Base ID
'Random Post', // Name
array( 'description' => __( 'Display random post in sidebar widget.', 'projectsengine' ), ) // Args
);
}
public function widget( $args, $instance ) {
// outputs the content of the widget
extract( $args );
$title = apply_filters( 'widget_title', $instance['title'] );
echo $before_widget;
if ( ! empty( $title ) ) {
echo $before_title . $title . $after_title;
}
$random = getRandomPost(); ?>
<div class="other-post other-post-widget">
<h5>you might like</h5>
<h2><?= $random->post_title; ?></h2>
<p><?= $random->post_excerpt; ?></p>
<a target="_blank" href="<?= site_url() . '/' . $random->post_name; ?>" class="button other-post-btn">read more</a>
</div>
<?php echo $after_widget;
}
public function form( $instance ) {
// outputs the options form in the admin
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( '', 'projectsengine' );
}
?>
<p>
<label for="<?php echo $this->get_field_name( '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 ) {
// processes widget options to be saved
$instance = array();
$instance['title'] = ( !empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
}
/**
* Return random post.
*
* @return int|WP_Post
*/
function getRandomPost() {
$posts = new WP_Query([
'post_type' => 'post',
'posts_per_page' => 1,
'orderby' => 'rand'
]);
$post = $posts->posts;
return $post[0];
}
// Register Foo_Widget widget
add_action( 'widgets_init', 'register_pe_random_post' );
function register_pe_random_post() {
register_widget( 'PE_Random_Post' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment