Crear un widget para wordpress

En este caso la cosa se complica, tenemos que tener un esqueleto que herede la clase widget. Pero básicamente es lo mismo, el código va donde el comentario:

class EntradasWidget extends WP_Widget {

function EntradasWidget() {
$widget_ops = array('classname' => 'EntradasWidget', 'description' => 'Muestra entrada aleatoria');
$this->WP_Widget('EntradasWidget', 'Entrada aleatoria con thumbnail', $widget_ops);
}

function form($instance) {
$instance = wp_parse_args((array) $instance, array('title' => ''));
$title = $instance['title'];
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?= _e('Title') ?>: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
}

function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
return $instance;
}

function widget($args, $instance) {
extract($args, EXTR_SKIP);

echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);

if (!empty($title))
echo $before_title . $title . $after_title;

// CóDIGO DEL WIDGET
$posts = get_posts(['orderby'=>'rand','numberposts'=>1]);
$post = $posts[0];
?><a href="<?= get_permalink($post); ?>" title="<?= $post->post_title; ?>"><?= $post->post_title; ?></a>
<?php
//FIN DEL CÓDIGO WIDGET
echo $after_widget;
}

}

add_action('widgets_init', create_function('', 'return register_widget("EntradasWidget");'));
?>

Un enlace que nos explica como crearlo desde cero:

Crear Widget en wordpress

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos