Custom widget Image upload Issue - php

A day before tomorrow, I developed a custom widget for my Recent WordPress theme. In that widget, have an image upload field with some other fields. I have done everything and the widget is working very well except one problem. When I am dragging the widget in sidebar and giving the information needed in all fields, its showing fine in front-end. But after that when I am trying to change the image from that widget back-end then the save button remain saved. Image doesn’t change.
Codes are below:
class Themeslug_About_Widget extends WP_widget{
public function __construct(){
parent::__construct('author_info', esc_html__( 'About Info Box', 'blogista' ), array(
'description' => esc_html__( 'About Info Box contain brief about Author/ Company.', 'blogista' ),
));
}
public function widget( $args, $instance ){
echo $args['before_widget'];
echo $args['before_title'] . $instance['title'] . $args['after_title'];
?>
<img src="<?php echo $instance['author_box_image']; ?>" alt="<?php echo $instance['title']; ?>" />
<div class="widget-content">
<h3 class="title">
<?php echo $instance['author_name']; ?>
</h3>
</div>
<?php
echo $args['after_widget'];
}
public function form( $instance ){
$title = '';
if( !empty( $instance['title'] ) ) {
$title = $instance['title'];
}
$author_box_image = '';
if( ! empty( $instance['author_box_image'] ) ) {
$author_box_image = $instance['author_box_image'];
}
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e( 'Title:', 'blogista' ); ?></label>
<input type="text" value="<?php echo esc_attr( $title ); ?>" name="<?php echo $this->get_field_name('title'); ?>" id="<?php echo $this->get_field_id('title'); ?>" class="widefat">
</p>
<p>
<button class="button button-primary" id="author_info_image"><?php _e( 'Upload Image', 'blogista' ); ?></button>
<input type="hidden" name="<?php echo $this->get_field_name('author_box_image'); ?>" id="<?php echo $this->get_field_id('author_box_image'); ?>" class="image_link" value="<?php echo esc_url( $author_box_image ); ?>" >
<div class="image_show">
<img src="<?php echo $instance['author_box_image']; ?>" width="200" height="auto" alt="">
</div>
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? esc_attr( $new_instance['title'] ) : '';
$instance['author_box_image'] = ( ! empty( $new_instance['author_box_image'] ) ) ? esc_url( $new_instance['author_box_image'] ) : '';
return $instance;
}
}
function themeslug_admin_enqueue_scrits(){
wp_enqueue_media();
wp_enqueue_script( 'admin_custom_script', get_theme_file_uri() . '/js/libs/admin_scripts.js', array( 'jquery' ), '1.0', true );
}
add_action( 'admin_enqueue_scripts', 'themeslug_admin_enqueue_scrits' );
Then added the below jQuery code:
(function($){
$(document).ready(function(){
$('button#author_info_image').on("click",function( e ){
e.preventDefault();
var imageUploader = wp.media({
'title' : 'Upload Author Image',
'button' : {
'text' : 'Set The Image'
},
'multiple' : false
});
imageUploader.open();
imageUploader.on("select", function(){
var image = imageUploader.state().get("selection").first().toJSON();
var link = image.url;
$("input.image_link").val( link );
$(".image_show img").attr('src', link);
});
});
});
}(jQuery))
Every thing is working fine first time but when trying to change the image then Widget save button remain saved.
Please Help.
Thanks in Advance.

I will Suggest you to follow my way to create your custom widget using image upload system.
public function widget( $args, $instance ) {
// Our variables from the widget settings
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Default title', 'text_domain' ) : $instance['title'] );
$image = ! empty( $instance['image'] ) ? $instance['image'] : '';
ob_start();
echo $args['before_widget'];
if ( ! empty( $instance['title'] ) ) {
echo $args['before_title'] . $title . $args['after_title'];
}
?>
<?php if($image): ?>
<img src="<?php echo esc_url($image); ?>" alt="">
<?php endif; ?>
<?php
echo $args['after_widget'];
ob_end_flush();
}
And the form function will be:
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'text_domain' );
$image = ! empty( $instance['image'] ) ? $instance['image'] : '';
?>
<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>
<p>
<label for="<?php echo $this->get_field_id( 'image' ); ?>"><?php _e( 'Image:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'image' ); ?>" name="<?php echo $this->get_field_name( 'image' ); ?>" type="text" value="<?php echo esc_url( $image ); ?>" />
<button class="upload_image_button button button-primary">Upload Image</button>
</p>
<?php
}
And here is the update function:
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['image'] = ( ! empty( $new_instance['image'] ) ) ? $new_instance['image'] : '';
return $instance;
}
As you can see, I’ve added a button underneath image input field with class “.upload_image_button”, but it will not work for now and to make it work, need to add our custom admin JavaScript.
First need to create javascript file and put it into your theme, let’s create a file, called our_admin.js in assets/js under your theme folder.
Next you will need to register and enqueue our script to make it load in the admin panel, so lets add few lines to widget class constructor function:
function __construct() {
// Add Widget scripts
add_action('admin_enqueue_scripts', array($this, 'scripts'));
parent::__construct(
'our_widget', // Base ID
__( 'Our Widget Title', 'text_domain' ), // Name
array( 'description' => __( 'Our Widget with media files', 'text_domain' ), ) // Args
);
}
And you will need then “scripts” function in our widget class:
public function scripts()
{
wp_enqueue_script( 'media-upload' );
wp_enqueue_media();
wp_enqueue_script('our_admin', get_template_directory_uri() . '/assets/js/our_admin.js', array('jquery'));
}
As you can notice, I added wp_enqueue_script( ‘media-upload’ ); and wp_enqueue_media(); to enqueue media library popup scripts.
And finally, here is js script, that will call WordPress media library popup and put selected image into the input field:
jQuery(document).ready(function ($) {
$(document).on("click", ".upload_image_button", function (e) {
e.preventDefault();
var $button = $(this);
// Create the media frame.
var file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select or upload image',
library: { // remove these to show all
type: 'image' // specific mime
},
button: {
text: 'Select'
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on('select', function () {
// We set multiple to false so only get one image from the uploader
var attachment = file_frame.state().get('selection').first().toJSON();
$button.siblings('input').val(attachment.url);
});
// Finally, open the modal
file_frame.open();
});
});
Now compare your code and you will see the error.
I will suggest to use Plugin to show author information to save your time.

Related

Some problems in custom widget

I made a custom widget for my template, which has an image upload section
For the first time, I upload an image, it displays correctly, without any problem, but when I want to change the image, it does not change, it displays the same image as before, that part of the image cannot be updated.
Thank you for your guidance
code PHP
<?php
class widget_author extends WP_Widget {
/**
* Register widget with WordPress.
*/
function __construct() {
parent::__construct(
'author', // Base ID
esc_html__( 'widget_test', 'text_domain' ), // Name
array( 'description' => esc_html__( 'widget test', 'text_domain' ), ) // Args
);
}
/**
* Front-end display of the widget.
*
* #param array $args Widget arguments.
* #param array $instance Saved values from the database.
*
* #see WP_Widget::widget()
*
*/
public function widget( $args, $instance ) {
$upload_image = strip_tags($instance['upload_image']);
echo $args['before_widget'];
if ( ! empty( $instance['title'] ) ) {
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
} ?>
<div class="thumb">
<?php
if ( ! empty( $instance['upload_image'] ) ) { ?>
<img src="<?php echo $upload_image; ?>"></a>
<?php } ?>
</div>
<?php
echo $args['after_widget'];
}
/**
* Back-end widget form.
*
* #param array $instance Previously saved values from the database.
*
* #see WP_Widget::form()
*
*/
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
$upload_image = ! empty( $instance['upload_image'] ) ? $instance['upload_image'] : '';
?>
<!-- Title -->
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
<?php esc_attr_e( 'Widget Title:', 'text_domain' ); ?>
</label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text"
value="<?php echo esc_attr( $title ); ?>">
</p>
<!-- Upload Image -->
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'upload_image' ) ); ?>">
<?php esc_attr_e( 'Image:', 'text_domain' ); ?>
</label>
<img class="<?= $this->id ?>_img" src="<?= (!empty($instance['upload_image'])) ? $instance['upload_image'] : ''; ?>" style="margin:0;padding:0;max-width:100%;display:block"/>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'upload_image' ) ); ?>"
name="<?php echo esc_attr( $this->get_field_name( 'upload_image' ) ); ?>" type="text"
value="<?= $instance['upload_image'] ?? ''; ?>">
<button id="<?= $this->id ?>" class="upload_image_button button button-primary" style="margin-top: 5px;">Upload Image</button>
</p>
<?php
}
/**
* Sanitize widget form values as they are saved.
*
* #param array $new_instance Values just sent to be saved.
* #param array $old_instance Previously saved values from the database.
*
* #return array Updated safe values to be saved.
* #see WP_Widget::update()
*
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';
$instance['upload_image'] = ( ! empty( $new_instance['upload_image'] ) ) ? sanitize_text_field( $new_instance['upload_image'] ) : '';
return $instance;
}
}
code java
jQuery(document).ready(function ($) {
$(document).on("click", ".upload_image_button", function (e) {
e.preventDefault();
var $button = $(this);
// Create the media frame.
var file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select or upload image',
library: { // remove these to show all
type: 'image' // specific mime
},
button: {
text: 'Select'
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on('select', function () {
// We set multiple to false so only get one image from the uploader
var attachment = file_frame.state().get('selection').first().toJSON();
$button.siblings('input').val(attachment.url);
});
// Finally, open the modal
file_frame.open();
});
});

ACF Custom Widget on Woocommerce Shop Page (Repeater)

I have a big issue with an ACF custom widget, I would like to setup a Repeater style using ACF Pro displayed in the Sidebar on the Shop page of WooCommerce platform. The problem is - it doesn't work. It doesn't display the image sub_field called "photoTest" in the page_sliders.
I downloaded the widget and tried to figure out this but I have no idea where is the problem.. ACF rule is linked with the widget, in the functions there is an absolute path to the custom widget but I think the problem might be with the custom widget itself so here is the code.
<?php
class ACF_Custom_Widget extends WP_Widget {
function __construct() {
parent::__construct(
'acf_custom_widget',
__('ACF Custom Widget', 'text_domain'),
array( 'description' => __( 'A custom ACF widget', 'text_domain' ), 'classname' => 'acf-custom-widget' ) // Args
);
}
public function widget( $args, $instance ) {
echo $args['before_widget'];
if ( !empty($instance['title']) ) {
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'];
}
echo get_field('title', 'widget_' . $args['widget_id']);?>
<?php
if ( is_shop() ){
$page_id = get_option( 'woocommerce_shop_page_id' );
}
else {
$page_id = get_the_ID();
}
if( have_rows('page_sliders', $page_id) ): ?>
<div id="carouselControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<?php while( have_rows('page_sliders', $page_id) ): the_row();
// vars
$image = get_sub_field('photoTest', $page_id);
?>
<div class="photo-wrap">
<img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt']); ?>" />
</div>
<?php endwhile; ?>
</div>
</div>
<?php endif; ?>
<?php
echo $args['after_widget'];
}
public function form( $instance ) {
if ( isset($instance['title']) ) {
$title = $instance['title'];
}
?>
<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;
}
}
add_action( 'widgets_init', function(){
register_widget( 'ACF_Custom_Widget' );
});
Please help..thank you.

Wordpress shortcode displays widget but not content

I am trying to create a shortcode that will display a current widget and it's contents. It seems to function perfectly fine for wordpress default widgets, however when it comes to my custom widgets it does not work. Any ideas on how to fix it?
Shortcode (I believe the issue stands with $widget_id not working on custom widgets):
function widget_shortcodes($atts) {
global $wp_widget_factory;//Connects to all registered widgets
$parts = shortcode_atts(array( //sets the attributes for the shortcode
'id' => '1', //sets the id field of the shortcode
'type' => 'text' //sets the type field of the shortcode
), $atts );
$widget_id = $atts['id']; //sets the widget id variable to the input id in the shortcode
//this if/elseif statement block checks to see the value of the type field and sets the widget type variable depending on the value
if($atts['type'] == 'calendar'){
$widget_type = 'WP_Widget_Calendar';
} elseif ($atts['type'] == 'posts') {
$widget_type = 'My_Recent_Posts_Widget';
} elseif ($atts['type'] == 'text') {
$widget_type = 'WP_Widget_Text';
} elseif ($atts['type'] == 'form') {
$widget_type = 'quickform_widget';
} elseif ($atts['type'] == 'newsletter') {
$widget_type = 'newsletter_widget';
} elseif ($atts['type'] == 'reviews') {
$widget_type = 'reviews_widget';
}
ob_start(); //initiates the object
if(!empty($widget_type)) {
the_widget($widget_type, $instance, array('widget_id'=> $widget_id)); //gets the widget if the type is correct
$widget_output = ob_get_contents(); //sets the widget output to the object content
} else { //if the type is not supported it displays an error message
echo "<p>Please make sure you have set a valid type in your shortcode.</p>";
echo "<p>Accepted Types: calendar, posts, text, form, newsletter and reviews.<p>";
$widget_output = ob_get_contents(); //sets the widget output to the object content
}
ob_end_clean(); //ends the object
return $widget_output; //returns the widget code
} add_shortcode('widget','widget_shortcodes');
Custom Widget:
<?php // Creating the widget
class newsletter_widget extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'newsletter_widget',
// Widget name will appear in UI
__('Newsletter', 'wpb_widget_domain'),
// Widget description
array( 'description' => __( 'Newsletter widget', 'wpb_widget_domain' ), )
);
}
// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
$code = apply_filters( 'widget_code', $instance['code'] );
$desc = apply_filters( 'widget_desc', $instance['desc'] );
?>
<aside class="widget widget_newsletter">
<h3><?php echo $title; ?></h3>
<p><?php echo ( $desc ); ?></p>
<?php echo do_shortcode($code);?>
</aside>
<?php }
// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'Receive our monthly newsletter', 'wpb_widget_domain' );
}
if ( isset( $instance[ 'code' ] ) ) {
$code = $instance[ 'code' ];
}
else {
$code = __( 'Form Code...', 'wpb_widget_domain' );
}
if ( isset( $instance[ 'desc' ] ) ) {
$desc = $instance[ 'desc' ];
}
else {
$desc = __( 'Newsletter description...', 'wpb_widget_domain' );
}
// Widget admin form?>
<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>
<p>
<label for="<?php echo $this->get_field_id( 'desc' ); ?>"><?php _e('Newsletter Description:'); ?></label>
<textarea class="widefat" id="<?php echo $this->get_field_id( 'desc' ); ?>" name="<?php echo $this->get_field_name( 'desc' ); ?>" type="text" value="<?php echo esc_attr( $desc ); ?>"><?php echo $desc;?></textarea>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'code' ); ?>"><?php _e( 'Form code:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'code' ); ?>" name="<?php echo $this->get_field_name( 'code' ); ?>" type="text" value="<?php echo esc_attr( $code ); ?>" />
</p>
<?php }
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['code'] = ( ! empty( $new_instance['code'] ) ) ? strip_tags( $new_instance['code'] ) : '';
$instance['desc'] = ( ! empty( $new_instance['desc'] ) ) ? strip_tags( $new_instance['desc'] ) : '';
return $instance;
}
}
// Register and load the widget
function newsletter_load_widget() {
register_widget( 'newsletter_widget' );
}
add_action( 'widgets_init', 'newsletter_load_widget' );?>

When uploading an image, the image doesn't change but the image URL is correct

I'm trying out wordpress widgets, and I took this code from https://vedmant.com/using-wordpress-media-library-in-widgets-options/. The widget is supposed to let you upload your own images via the wordpress media library. The code works to open up the media library, upload an image and choose it, but the image won't change to show the new image.
Here's the code (also on the site):
I read some other treads on similar things, and tried to look up refreshing widgets, but I can't seem to find the answer I'm looking for. I think the problem is that the textbox will fill with the image URL but it won't refresh because Wordpress thinks nothing changed. Any ideas on what I can do?
<?php
add_action( 'widgets_init', 'myw_init' );
function myw_init() {
register_widget( 'my_widget' );
}
class my_widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
function __construct() {
// Add Widget scripts
add_action('admin_enqueue_scripts', array($this, 'scripts'));
parent::__construct(
'my_widget', // Base ID
__( 'Our Widget Title', 'text_domain' ), // Name
array( 'description' => __( 'Our Widget with media files', 'text_domain' ), ) // Args
);
}
/**
* Enqueue scripts
*/
public function scripts()
{
wp_enqueue_script( 'media-upload' );
wp_enqueue_media();
wp_enqueue_script('mfc-media-upload', get_template_directory_uri() . '/../../plugins/my-featured-content/mfc-media-upload.js', array('jquery'));
}
/**
* Outputs the content of the widget
*
* #param array $args
* #param array $instance
*/
public function widget( $args, $instance ) {
// Our variables from the widget settings
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Default title', 'text_domain' ) : $instance['title'] );
$image = ! empty( $instance['image'] ) ? $instance['image'] : '';
ob_start();
echo $args['before_widget'];
if ( ! empty( $instance['title'] ) ) {
echo $args['before_title'] . $title . $args['after_title'];
}
?>
<?php if($image): ?>
<img src="<?php echo esc_url($image); ?>" alt="">
<?php endif; ?>
<?php
echo $args['after_widget'];
ob_end_flush();
}
/**
* Outputs the options form on admin
*
* #param array $instance The widget options
*/
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'text_domain' );
$image = ! empty( $instance['image'] ) ? $instance['image'] : '';
?>
<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>
<p>
<label for="<?php echo $this->get_field_id( 'image' ); ?>"><?php _e( 'Image:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'image' ); ?>" name="<?php echo $this->get_field_name( 'image' ); ?>" type="text" value="<?php echo esc_url( $image ); ?>" />
<button class="upload_image_button button button-primary">Upload Image</button>
</p>
<?php
}
/**
* Processing widget options on save
*
* #param array $new_instance The new options
* #param array $old_instance The previous options
*
* #return array
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['image'] = ( ! empty( $new_instance['image'] ) ) ? $new_instance['image'] : '';
return $instance;
}
}
And for the jQuery:
jQuery(document).ready(function ($) {
$(document).on("click", ".upload_image_button", function (e) {
e.preventDefault();
var $button = $(this);
// Create the media frame.
var file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select or upload image',
library: { // remove these to show all
type: 'image' // specific mime
},
button: {
text: 'Select'
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on('select', function () {
// We set multiple to false so only get one image from the uploader
var attachment = file_frame.state().get('selection').first().toJSON();
$button.siblings('input').val(attachment.url);
});
// Finally, open the modal
file_frame.open();
});
});
You can add a query parameter to the image URL to force it to be unique, e.g.:
<img src="<?php echo esc_url($image); ?>?<?php echo time() ?>" alt="">

How to create a custom WordPress widget with widget options

Trying to figure out the proper way of creating a very simple (reusable) WordPress Widget. Found this article by wpbeginner that seems to be the most comprehensive: http://goo.gl/7O8Izg
// Creating the widget
class wpb_widget extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'wpb_widget',
// Widget name will appear in UI
__('WPBeginner Widget', 'wpb_widget_domain'),
// Widget description
array( 'description' => __( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), )
);
}
// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
// This is where you run the code and display the output
echo __( 'Hello, World!', 'wpb_widget_domain' );
echo $args['after_widget'];
}
// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'wpb_widget_domain' );
}
// Widget admin form
?>
<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
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class wpb_widget ends here
// Register and load the widget
function wpb_load_widget() {
register_widget( 'wpb_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );
My question, how to include two widget options and their admin-form values (ex. custom number/text and it's font color) in the most proper way?
To have multiple options, update 3 sections from your above code
1) The front end
public function widget( $args, $instance ) {
//store the options in variables
$option1 = $instance['option1'];
$option2 = $instance['option2'];
// before widget (defined by theme)
echo $args['before_widget'];
//use your options
//(e.g. a paragraph with option1 as the text and option2 as its class for CSS)
//don't forget error/empty content handling/filters
echo "<p class='" . $option2 . "'>" . $option1 . "</p>";
// after widget (defined by theme)
echo $args['after_widget'];
}
2) The Backend w/ Form
//
public function form( $instance ) {
//Check if option1 exists, if its null, put "new option1" for use in the form
if ( isset( $instance[ 'option1' ] ) ) {
$option1 = $instance[ 'option1' ];
}
else {
$option1 = __( 'new option1', 'wpb_widget_domain' );
}
//Repeat for option2
if ( isset( $instance[ 'option2' ] ) ) {
$option1 = $instance[ 'option2' ];
}
else {
$option1 = __( 'new option2', 'wpb_widget_domain' );
}
<p>
<label for="<?php echo $this->get_field_id( 'option1' ); ?>"><?php _e( 'Option1:' ); ?</label>
<input class="widefat" id="<?php echo $this->get_field_id( 'option1' ); ?>" name="<?php echo $this->get_field_name( 'option1' ); ?>" type="text" value="<?php echo esc_attr( $option1 ); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id( 'option2' ); ?>"><?php _e( 'Option2:' ); ?</label>
<input class="widefat" id="<?php echo $this->get_field_id( 'option2' ); ?>" name="<?php echo $this->get_field_name( 'option2' ); ?>" type="text" value="<?php echo esc_attr( $option2 ); ?>" />
</p>
3) The function that saves your new widget settings
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['option1'] = ( ! empty( $new_instance['option1'] ) ) ? strip_tags( $new_instance['option1'] ) : '';
$instance['option2'] = ( ! empty( $new_instance['option2'] ) ) ? strip_tags( $new_instance['option2'] ) : '';
return $instance;
}
Essentially, you just have to repeat the right things and make sure you hit all the 3 key areas. Hope this helps.
It is simple method to create custom widget in wordpress.
This is widget for commemted post.
<?php
// Creating the widget
class commented_news_sidebar extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'commented_news_sidebar',
// Widget name will appear in UI
__('Commented News Widget', 'wpb_widget_domain'),
// Widget description
array( 'description' => __( 'Your site’s Most Commented News.', 'wpb_widget_domain' ), )
);
}
// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
if ( ! isset( $args['widget_id'] ) ) {
$args['widget_id'] = $this->id;
}
/*$the_query = new WP_Query(array( 'orderby' => 'comment_count', 'order'=> 'DESC' ));*/
$commentpost = new WP_Query( apply_filters( 'widget_posts_args', array(
'cat' => $instance['showcommentedcat'],
'orderby' => 'comment_count',
'posts_per_page' => 3,
'order' => 'DESC',
/* 'post_status' => 'publish',
*/
) ) );
if ($commentpost->have_posts()) :
?>
<div class="nav-box"> <h4><?php echo $instance['title'];?></h4></h4></div><!-- nav-box -->
<?php
$postthumb_id = null;
$con = null;
$img_url = null;
while ( $commentpost->have_posts() ) : $commentpost->the_post();
?>
<?php
$postthumb_id = get_post_thumbnail_id( get_the_ID());
$con = get_the_content($postthumb_id);
/*
$comments_count = wp_count_comments(get_the_ID());
print_r($comments_count);
*/
$img_url = wp_get_attachment_image_src( $postthumb_id , 'most-comment-img-size');
?>
<div class="comm-most"><!-- comm-most -->
<?php $commented_cat_nm = get_cat_name($instance['showcommentedcat']);?>
<a href="<?php the_permalink(); ?>">
<img src="<?php echo $img_url[0]; ?>" alt="">
<span><?php echo $commented_cat_nm; ?></span>
<p><?php get_the_title() ? the_title() : the_ID(); ?></p>
</a>
</div><!-- comm-most -->
<?php endwhile; ?>
<?php
// Reset the global $the_post as this query will have stomped on it
wp_reset_postdata();
endif;
}
// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'wpb_widget_domain' );
}
$oldcat = $instance['showcommentedcat'];
// Widget admin form
?>
<?php
$categories = get_categories( array(
'orderby' => 'name',
) );
?>
<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 ); ?>" />
<br>
<label for="<?php echo $this->get_field_id( 'showcommentedcat' ); ?>"><?php _e( 'Category:' ); ?></label>
<select id="<?php echo $this->get_field_id('showcommentedcat'); ?>" name="<?php echo $this->get_field_name('showcommentedcat'); ?>" class="widefat" >
<?php foreach ( $categories as $category ) {?>
<option <?php selected($instance['showcommentedcat'], esc_html( $category->name ));?> value="<?php echo $category->term_id ; ?>" <?php if($oldcat == $category->term_id){echo "selected";}?>><?php echo $category->name ; ?> </option>
<?php } ?>
</select>
</p>
<?php
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['showcommentedcat'] = $new_instance['showcommentedcat'];
return $instance;
}
} // Class commented_news_sidebar ends here
// Register and load the widget
function wpb_load_widget_commented_news() {
register_widget( 'commented_news_sidebar' );
}
add_action( 'widgets_init', 'wpb_load_widget_commented_news' );

Categories