Wordpress how to set default values for widgets? - wordpress

Im trying to make my own widget. But i found out that this is not so easy. I'm trying to set default values but i have no idea how to do this.
Yes, i have Googled a lot. I'm almost trying for 1 week to get my own options page and custom widgets, but im not succeeding.
so back to my question, this is my code now:
class Superdeal_Widget extends WP_Widget {
public function __construct()
{
parent::__construct(
'Superdeal-widget',
'Superdeal Widget',
array(
'description' => 'Superdeal widget'
),
array (
'width' => 400,
'height' => 350
)
);
}
public function widget( $args, $instance )
{
// basic output just for this example
echo '<p>'.$instance['titel'].' '.$instance['superdeal'].'</p>';
}
public function form( $instance )
{
// removed the for loop, you can create new instances of the widget instead
?>
<p>
<label for="<?php echo $this->get_field_id('titel'); ?>">Titel</label><br />
<input type="text" name="<?php echo $this->get_field_name('titel'); ?>" id="<?php echo $this->get_field_id('titel'); ?>-title" value="<?php echo $instance['titel']; ?>" class="widefat" />
</p>
<p>
<label for="<?php echo $this->get_field_id('url'); ?>">Url</label><br />
<input type="text" name="<?php echo $this->get_field_name('url'); ?>" id="<?php echo $this->get_field_id('url'); ?>-url" value="<?php echo $instance['url']; ?>" class="widefat" />
</p>
<p>
<label for="<?php echo $this->get_field_id('superdeal'); ?>">Superdeal tekst</label><br />
<input type="text" name="<?php echo $this->get_field_name('superdeal'); ?>" id="<?php echo $this->get_field_id('superdeal'); ?>-title" value="<?php echo $instance['superdeal']; ?>" class="widefat" />
</p>
<?php
}
}
// end class
// init the widget
add_action( 'widgets_init', create_function('', 'return register_widget("Superdeal_Widget");') );
PS: if you know a good tutorial which shows how to make you own options page / declare properties / makeing custom widgets, i would love to hear from you. Because all the tutorials i have followd are old, obscure or way too complicated.
Thank you guys!

This should help you → widget tutorial
Note on this line from form() function:
$instance = wp_parse_args( (array) $instance, array( 'title' => 'DEFAULT_VALUE_HERE' ) );
You can add several instances like:
array( 'title' => 'DEFAULT_VALUE_HERE', 'name' => 'DEFAULT_VALUE_HERE')
Hope this would help you going.

Related

Entering detail information on the created order

I want to create a field where the customer can write the reason for canceling a created order. The code below appears in other orders as well, due to the customer's own knowledge. I made several attempts to register the order, but I could not get the result I wanted. I thought about "update_post_meta" and "order_id" but I guess I failed. Also, I couldn't decide where it would make sense for this area to appear on the admin page. Thanks.
// Display user custom field
add_action( 'woocommerce_order_details_before_order_table', 'add_user_custom_url_field_to_order' );
function add_user_custom_url_field_to_order( $order ) {
global $current_user;
$custom_url = get_user_meta( $current_user->ID, 'custom_URL', true );
?>
<form method="post">
<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
<label for="custom_URL"><?php _e( 'URL', 'woocommerce' ); ?></label>
<input type="text" name="custom_URL" id="custom_URL" value="<?php echo $custom_url; ?>" />
</p>
<input type="submit" name="submit-custom_URL" value="<?php _e('RUN', 'woocommerce'); ?>" /><br/>
</form>
<?php
}
// Save the field as custom user data
add_action( 'template_redirect', 'save_user_custom_url_field_from_order' );
function save_user_custom_url_field_from_order() {
global $current_user;
if( isset($_POST['custom_URL']) ){
update_user_meta( $current_user->ID, 'custom_URL', sanitize_url( $_POST['custom_URL'] ) );
wc_add_notice( __("Submitted data has been saved", "woocommerce") );
}
}
Code source: https://stackoverflow.com/a/62777930/14597323

How to create WordPress widget using custom menu select

I'm creating a custom widget for WordPress but am wanting to use the same select menu as the default Custom Menu widget does. So far what I have works except the selected menu isn't being saved or displayed on the frontend. Any help or direction with this is appreciated. Thanks.
For brevity, I've removed extra widget options, so this is basically going to look very close to the Custom Menu widget:
class kedc_mini_sitemap extends WP_Widget {
/*constructor*/
function kedc_mini_sitemap() {
parent::WP_Widget(false, $name = 'Mini Sitemap');
}
/**/
function widget($args, $instance) {
extract( $args );
// widget options
$title = apply_filters('widget_title', $instance['title']);
$nav_menu1 = ! empty( $instance['nav_menu'] ) ? wp_get_nav_menu_object( $instance['nav_menu'] ) : false;
$checkbox = $instance['checkbox'];
echo $before_widget;
if ($title) {
echo $before_title . $title . $after_title;
}
if ($nav_menu1) {
echo wp_nav_menu( array( 'fallback_cb' => '', 'menu' => $nav_menu1 ) );
}
if ($checkbox == true) {
echo 'This message is displayed if our checkbox is checked.';
}
echo $after_widget;
}
/* saves options chosen from the widgets panel */
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['nav_menu'] = (int) $new_instance['nav_menu'];
$instance['checkbox'] = strip_tags($new_instance['checkbox']);
return $instance;
}
/* display widget in widgets panel */
function form($instance) {
$title = esc_attr($instance['title']);
$nav_menu1 = isset( $instance['nav_menu'] ) ? $instance['nav_menu'] : '';
$checkbox = esc_attr($instance['checkbox']);
$menus1 = get_terms( 'nav_menu', array( 'hide_empty' => false ) );
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget 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 $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('nav_menu'); ?>"><?php _e('Select Menu:'); ?></label>
<select id="<?php echo $this->get_field_id('nav_menu'); ?>" name="<?php echo $this->get_field_name('nav_menu'); ?>">
<?php
foreach ( $menus1 as $menu1 ) {
echo '<option value="' . $menu1->term_id . '"'
. selected( $nav_menu, $menu1->term_id, false )
. '>'. $menu1->name . '</option>';
}
?>
</select>
</p>
<p>
<input id="<?php echo $this->get_field_id('checkbox'); ?>" name="<?php echo $this->get_field_name('checkbox'); ?>" type="checkbox" value="1" <?php checked( '1', $checkbox ); ?>/>
<label for="<?php echo $this->get_field_id('checkbox'); ?>"><?php _e('Do you want this to display as 2 columns?'); ?></label>
</p>
<?php
}
}
// register widget
add_action('widgets_init', create_function('', 'return register_widget("kedc_mini_sitemap");'));
You have a typo in the form() function: $nav_menu1 and $nav_menu.
Use more meaningful, strict and descriptive names for your variables. For example, $menus1 could be called $get_nav_menus.
Use a good IDE, like NetBeans or similar, and check the WordPress Coding Standards Handbook.
Oh, yes, your code is dumping PHP Notices, always develop with WP_DEBUG enabled.

$instance in wordpress widget form method is null

I am new to wordpress widget development and learning from tutsplus videos on the go. I am trying to create a simple widget for my website. So far I am following every steps from the video but still I am getting following error and the form is not saving the values.
Warning: extract() expects parameter 1 to be array, null given in C:\Program Files\Ampps\www\test\wp-content\plugins\first\index.php on line 50
This is the from method
public function form($instance){
extract($instance);
?>
<p>
<lable for="<?php echo $this->get_field_id('ap_title_text');?>">Title Text: </lable>
<input type="text" class="widefat" id="<?php echo $this->get_field_id('ap_title_text');?>" name="<?php echo $this->get_field_name('ap_title_text');?>" value="<?php if(isset($ap_title_text)) echo esc_attr($ap_title_text);?>" />
</p>
<?php
So far, I have just created the constructor and registered the widget. There was no error displayed till this step in the video. And every website I googled for this problem showed similar steps. I don't understand why it is showing error on my system.
I am using wordpress 3.5.2 downloaded yesterday and using php5.3.
EDIT ::
Here is the code.
class SidebarWidget extends WP_Widget{
function __construct()
{
$options = array(
'description' => 'Simplest way to start working from any page',
'name' => 'Sidebar Widget'
);
parent::__construct('appSidebarWidget', '', $options);
}
public function form($instance)
{
extract($instance);
?>
<p>
<label for="<?php echo $this->get_field_id('ap_title_text'); ?>" >Title Text: </lable>
<input type="text" class="widefat" id="<?php echo $this->get_field_id('ap_title_text');?>" name="<?php echo $this->get_field_name('ap_title_text');?>" value="<?php if(isset($ap_title_text)) echo esc_attr($ap_title_text);?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('ap_app_name'); ?>" >app Name: </lable>
<input type="text" class="widefat" id="<?php echo $this->get_field_id('ap_app_name');?>" name="<?php echo $this->get_field_name('ap_app_name');?>" value="<?php if(isset($ap_app_name)) echo esc_attr($ap_app_name);?>" />
</p>
<?php
}
public function widget($args, $instance)
{
extract($args);
extract($instance);
$display_gadget = "<iframe src='http://$appURL' width='150px' height='200px' scrolling='auto' frameborder='0' allowtransparency='true'></iframe>";
if(empty($ap_title_text)){$ap_title_text = "Schedule Now";}
echo $before_widget;
echo $before_title.$ap_title_text.$after_title;
echo $display_gadget;
echo $after_widget;
}
}
add_action('widgets_init','appRegisterWidget');
function appRegisterWidget()
{
register_widget('appSidebarWidget');
}
I still haven't been able to get it working. However the actual project for which i was learning this, works as expected. I would still like to know what is wrong with this one. I nearly lost my job because of this.
Also, can anyone guide me to call a custom javascript function from a button on widget being displayed. Basically my purpose is to display a button on the widget rendered by the information on the form. When someone click the button, It should display an overlay with message.
In the following code
add_action('widgets_init','appRegisterWidget');
function appRegisterWidget()
{
register_widget('appSidebarWidget'); <--
}
Change it to
register_widget('SidebarWidget');
I've added a url text box in the widget setup form and it's working, (full modified code given below)
class SidebarWidget extends WP_Widget{
function __construct()
{
$options = array(
'description' => 'Simplest way to start working from any page',
'name' => 'Sidebar Widget'
);
parent::__construct('appSidebarWidget', '', $options);
}
public function form($instance)
{
extract($instance);
?>
<p>
<label for="<?php echo $this->get_field_id('ap_title_text'); ?>" >Title Text: </lable>
<input type="text" class="widefat" id="<?php echo $this->get_field_id('ap_title_text');?>" name="<?php echo $this->get_field_name('ap_title_text');?>" value="<?php if(isset($ap_title_text)) echo esc_attr($ap_title_text);?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('ap_app_name'); ?>" >App Name: </lable>
<input type="text" class="widefat" id="<?php echo $this->get_field_id('ap_app_name');?>" name="<?php echo $this->get_field_name('ap_app_name');?>" value="<?php if(isset($ap_app_name)) echo esc_attr($ap_app_name);?>" />
</p>
<!-- New text box added -->
<p>
<label for="<?php echo $this->get_field_id('ap_app_url'); ?>" >App Url: </lable>
<input type="text" class="widefat" id="<?php echo $this->get_field_id('ap_app_url');?>" name="<?php echo $this->get_field_name('ap_app_url');?>" value="<?php if(isset($ap_app_url)) echo esc_attr($ap_app_url);?>" />
</p>
<?php
}
public function widget($args, $instance)
{
extract($args);
extract($instance);
$display_gadget = "<iframe src='http://" . $ap_app_url . "' width='150px' height='200px' scrolling='auto' frameborder='0' allowtransparency='true'></iframe>";
if(empty($ap_title_text)){$ap_title_text = "Schedule Now";}
echo $before_widget;
echo $before_title.$ap_title_text.$after_title;
echo $display_gadget;
echo $after_widget;
}
}
add_action('widgets_init','appRegisterWidget');
function appRegisterWidget()
{
register_widget('SidebarWidget');
}
Screen shot of working example given below
The code is crashing because the variable $instance is not an array. The extract() function has to receive an array in order to do it's job. That much is clear and very simple.
The problem is that nobody can help you explain why $instance is null unless you provide the code which calls the form() function. There could be a million reasons why $instance is not an array.
The form() function is being called by the WP_Widgets object.
$instance could also always be null in the form method if you have an empty update function. This may not relate to this question, but please check whether that is the issue if you run into a similar issue.

Creating an Unwrapped Widget

I'm trying to create a widget similar to the text widget but I don't want it to be wrapped and I don't want any divs or formatting added around it. This will be used for javascript right before the closing tag so I'm just trying to have the plain/basic info thats typed into the widget. What else do I need besides what I have below? Did I do this right?
function 123_widgets_init() {
register_sidebar( array(
'name' => __( 'Scripts', '123' ),
'id' => 'sidebar-1',
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
) );
}
add_action( 'widgets_init', '123_widgets_init' );
Yes , you did right . any text widget can take javascript - if you want to get rid of the divs and p tags and classes - your code should be enough.
you can also use some filters to clean other things .
Actually, I had a code for such a widget - I do not remember from which website I took it (some snippet repository) but it is basically the text widget duplicated with some small changes.
<?php
/*
Plugin Name: Text widget for Javascript
Plugin URI: Unknown
Description: Adds a Text widget with Javascript support - basically empty all divs classes etc.
Version: 3.1
Author: Unknown (code source unknown. compiled by Obmerk99)
Author URI: Unknown
License: GPL2
Network: true
*/
/**********************************************
* Text widget class with small twicks for JS *
**********************************************/
class WP_Widget_Text_For_JS extends WP_Widget {
function __construct() {
$widget_ops = array('classname' => 'widget_text', 'description' => __('Javascript Text Widget'));
$control_ops = array('width' => 400, 'height' => 350);
parent::__construct('text', __('Text'), $widget_ops, $control_ops);
}
function widget( $args, $instance ) {
extract($args);
$title = apply_filters( 'widget_title', empty($instance['title']) ? '' : $instance['title'], $instance, $this->id_base);
$text = apply_filters( 'widget_text', $instance['text'], $instance );
$before_widget = ''; $after_widget =''; $before_title=''; $after_title='';$after_widget=''; //empty all
echo $before_widget;
if ( !empty( $title ) ) { echo $before_title . $title . $after_title; } ?>
<div class="textwidget"><?php echo $instance['filter'] ? wpautop($text) : $text; ?></div>
<?php
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['text'] = $new_instance['text'];
$instance['filter'] = isset($new_instance['filter']);
return $instance;
}
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( 'title' => '', 'text' => '' ) );
$title = strip_tags($instance['title']);
$text = esc_textarea($instance['text']);
?>
<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>
<textarea class="widefat" rows="16" cols="20" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>"><?php echo $text; ?></textarea>
<p><input id="<?php echo $this->get_field_id('filter'); ?>" name="<?php echo $this->get_field_name('filter'); ?>" type="checkbox" <?php checked(isset($instance['filter']) ? $instance['filter'] : 0); ?> /> <label for="<?php echo $this->get_field_id('filter'); ?>"><?php _e('Automatically add paragraphs'); ?></label></p>
<?php
}
}
function wp_o99_javascript_text_widget(){
// unregister_widget('WP_Widget_Text'); // Only if you really want to .
register_widget('WP_Widget_Text_For_JS');
}
add_action('widgets_init', 'wp_o99_javascript_text_widget', 1);
?>
Use my plugin Magic Widgets. It has a text widget which doesn’t use the sidebar parameters, and it creates special widget areas in the header and footer of the front-end and back-end views.
You can take the plain widget from GitHub.
There are a lot of steps left to get to where you want
Create a new sidebar-xxx.php file that calls your sidebar you created
Create a widget to drop into that sidebar.
Call get_sidebar('xxx'); where you want it to display the widgets in your sidebar.
When creating the sidebar file or the widget you can exclude adding formatting or wrappers and just echo the input from the widget
http://codex.wordpress.org/Widgets_API

Wordpress - Category list order in post edit page

I want to stop WordPress re-ordering the category list in the admin > post edit page. The default behaviour is to take the categories assigned to the post out of their natural parent/child flow and put them at the top of the list. I want to stop this happening as it is confusing when the category structure is big.
Any thoughts?
Thanks.
While the above are great alternative solutions, especially if you want more control over the taxonomy checklist metabox, I think the simplest solution would be the following:
function taxonomy_checklist_checked_ontop_filter ($args)
{
$args['checked_ontop'] = false;
return $args;
}
add_filter('wp_terms_checklist_args','taxonomy_checklist_checked_ontop_filter');
And that should take care of that!
What version of Wordpress are you using? Wordpress 3.04 provides the Parent/Child tree on the Post Edit page. Are you sure you also aren't viewing the "Most Used" tab?
Nevermind, I see exactly the problem you are talking about, which show up after the post is saved:
Alright, try pasting this into the functions.php in your theme:
// remove the old box
function remove_default_categories_box() {
remove_meta_box('categorydiv', 'post', 'side');
}
add_action( 'admin_head', 'remove_default_categories_box' );
// add the new box
function add_custom_categories_box() {
add_meta_box('customcategorydiv', 'Categories', 'custom_post_categories_meta_box', 'post', 'side', 'low', array( 'taxonomy' => 'category' ));
}
add_action('admin_menu', 'add_custom_categories_box');
/**
* Display CUSTOM post categories form fields.
*
* #since 2.6.0
*
* #param object $post
*/
function custom_post_categories_meta_box( $post, $box ) {
$defaults = array('taxonomy' => 'category');
if ( !isset($box['args']) || !is_array($box['args']) )
$args = array();
else
$args = $box['args'];
extract( wp_parse_args($args, $defaults), EXTR_SKIP );
$tax = get_taxonomy($taxonomy);
?>
<div id="taxonomy-<?php echo $taxonomy; ?>" class="categorydiv">
<ul id="<?php echo $taxonomy; ?>-tabs" class="category-tabs">
<li class="tabs"><?php echo $tax->labels->all_items; ?></li>
<li class="hide-if-no-js"><?php _e( 'Most Used' ); ?></li>
</ul>
<div id="<?php echo $taxonomy; ?>-pop" class="tabs-panel" style="display: none;">
<ul id="<?php echo $taxonomy; ?>checklist-pop" class="categorychecklist form-no-clear" >
<?php $popular_ids = wp_popular_terms_checklist($taxonomy); ?>
</ul>
</div>
<div id="<?php echo $taxonomy; ?>-all" class="tabs-panel">
<?php
$name = ( $taxonomy == 'category' ) ? 'post_category' : 'tax_input[' . $taxonomy . ']';
echo "<input type='hidden' name='{$name}[]' value='0' />"; // Allows for an empty term set to be sent. 0 is an invalid Term ID and will be ignored by empty() checks.
?>
<ul id="<?php echo $taxonomy; ?>checklist" class="list:<?php echo $taxonomy?> categorychecklist form-no-clear">
<?php
/**
* This is the one line we had to change in the original function
* Notice that "checked_ontop" is now set to FALSE
*/
wp_terms_checklist($post->ID, array( 'taxonomy' => $taxonomy, 'popular_cats' => $popular_ids, 'checked_ontop' => FALSE ) ) ?>
</ul>
</div>
<?php if ( !current_user_can($tax->cap->assign_terms) ) : ?>
<p><em><?php _e('You cannot modify this taxonomy.'); ?></em></p>
<?php endif; ?>
<?php if ( current_user_can($tax->cap->edit_terms) ) : ?>
<div id="<?php echo $taxonomy; ?>-adder" class="wp-hidden-children">
<h4>
<a id="<?php echo $taxonomy; ?>-add-toggle" href="#<?php echo $taxonomy; ?>-add" class="hide-if-no-js" tabindex="3">
<?php
/* translators: %s: add new taxonomy label */
printf( __( '+ %s' ), $tax->labels->add_new_item );
?>
</a>
</h4>
<p id="<?php echo $taxonomy; ?>-add" class="category-add wp-hidden-child">
<label class="screen-reader-text" for="new<?php echo $taxonomy; ?>"><?php echo $tax->labels->add_new_item; ?></label>
<input type="text" name="new<?php echo $taxonomy; ?>" id="new<?php echo $taxonomy; ?>" class="form-required form-input-tip" value="<?php echo esc_attr( $tax->labels->new_item_name ); ?>" tabindex="3" aria-required="true"/>
<label class="screen-reader-text" for="new<?php echo $taxonomy; ?>_parent">
<?php echo $tax->labels->parent_item_colon; ?>
</label>
<?php wp_dropdown_categories( array( 'taxonomy' => $taxonomy, 'hide_empty' => 0, 'name' => 'new'.$taxonomy.'_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => '— ' . $tax->labels->parent_item . ' —', 'tab_index' => 3 ) ); ?>
<input type="button" id="<?php echo $taxonomy; ?>-add-submit" class="add:<?php echo $taxonomy ?>checklist:<?php echo $taxonomy ?>-add button category-add-sumbit" value="<?php echo esc_attr( $tax->labels->add_new_item ); ?>" tabindex="3" />
<?php wp_nonce_field( 'add-'.$taxonomy, '_ajax_nonce-add-'.$taxonomy, false ); ?>
<span id="<?php echo $taxonomy; ?>-ajax-response"></span>
</p>
</div>
<?php endif; ?>
</div>
<?php
}
The only real change was adding 'checked_ontop' => FALSE to the args in wp_terms_checklist() function in the middle of that mess. Everything else is the original post_categories_meta_box() function.
(You could just modify the original post_categories_meta_box() in /wp-admin/includes/meta-boxes.php, but it is not recommended to mess with core and adding/removing actions as above is the proper way to do it.
There's a plugin that does just this http://wordpress.org/extend/plugins/category-checklist-tree/

Resources