Thứ Tư, 8 tháng 2, 2017

Hướng dẫn làm Widget Plugin cho Wordpress - Phần 1

Step 1: How to create a plugin

I recently created a plugin called “Freelancer Widgets Bundle“, and some people asked me how to create such a plugin, so I decided to write this post. First step is the creation of the plugin. And as you’ll see, it’s the not the hardest part. A plugin is extra code added to WordPress once you activate it. WordPress creates a loop through a folder to retrieve all available plugins and list them in the back office. To create your plugin, you’ll need an editor such as Coda (Mac), or Dreamweaver (PC & Mac). I recommend you to create your plugin in a local install of WordPress, making it on a live server can cause some troubles if you make an error. So please, wait to test our plugin before placing on it your hosting.
Open now the folder wp-content/plugins. This where you are going to add your plugin. Create a new directory and call it “widget-plugin” (actually, this name can be whatever you want). Even if our plugin will only have one single file, it’s always better to use a folder for each plugin. In your directory, create a new file called “widget-plugin.php” (this name can be changed too), and open it. We are now about to add our first lines of code. The definition of a plugin under WordPress follows some rules that you can read here on the codex. Here is how WordPress defines a plugin:
<?php
/*
Plugin Name: Name Of The Plugin
Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
Description: A brief description of the Plugin.
Version: The Plugin's Version Number, e.g.: 1.0
Author: Name Of The Plugin Author
Author URI: http://URI_Of_The_Plugin_Author
License: A "Slug" license name e.g. GPL2
*/
?>
So, we have to modify this code to make it fit our needs:
<?php
/*
Plugin Name: Widget Plugin
Plugin URI: http://www.wpexplorer.com/
Description: A simple plugin that adds a simple widget
Version: 1.0
Author: WPExplorer
Author URI: http://www.wpexplorer.com/
License: GPL2
*/
?>
Save your file. By only adding code to our widget-plugin.php file we have created a plugin! Well, for now the plugin doesn’t do anything, but WordPress recognizes it. To make sure it’s the case, go your administration, and go under “Plugins” menu. If your plugin appears in the plugins list you’re good, otherwise make sure you followed my instructions and try again. You can now activate the plugin.

Step 2: Create the Widget

We are now going to create the widget itself. This widget will be a PHP class extending the core WordPress class WP_Widget. Basically, our widget will be defined this way:
class wp_my_plugin extends WP_Widget {

 // constructor
 function wp_my_plugin() {
  /* ... */
 }

 // widget form creation
 function form($instance) { 
 /* ... */
 }

 // widget update
 function update($new_instance, $old_instance) {
  /* ... */
 }

 // widget display
 function widget($args, $instance) {
  /* ... */
 }
}

// register widget
add_action('widgets_init', create_function('', 'return register_widget("wp_my_plugin");'));
This code gives WordPress all the information the system needs to be able to use the widget:
  1. The constructor, to initiate the widget
  2. The form() function to create the widget form in the administration
  3. The update() function, to save widget data during edition
  4. And the widget() function to display the widget content on the front-end

1 – The constructor

The constructor is the part of code that defines the widget name, so we’ll only add one line of code to it, to make it look like this:
// constructor
    function wp_my_plugin() {
        parent::WP_Widget(false, $name = __('My Widget', 'wp_widget_plugin') );
    }
Please not the use of __(). This function is use by WordPress for translation. I really recommend you to always use these functions, to make your theme fully translatable.

2 – The form() function

This function is the one that creates the widget in the WordPress administration, this is were you’ll enter your data to be displayed on the the website. For now I’m just going to explain you ho to add text fields and text areas. We’ll see check-box, drop-down  select and other methods in a next post. Here is what form’) must contain:
// widget form creation
function form($instance) {

// Check values
if( $instance) {
     $title = esc_attr($instance['title']);
     $text = esc_attr($instance['text']);
     $textarea = esc_textarea($instance['textarea']);
} else {
     $title = '';
     $text = '';
     $textarea = '';
}
?>

<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget Title', 'wp_widget_plugin'); ?></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('text'); ?>"><?php _e('Text:', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>" type="text" value="<?php echo $text; ?>" />
</p>

<p>
<label for="<?php echo $this->get_field_id('textarea'); ?>"><?php _e('Textarea:', 'wp_widget_plugin'); ?></label>
<textarea class="widefat" id="<?php echo $this->get_field_id('textarea'); ?>" name="<?php echo $this->get_field_name('textarea'); ?>"><?php echo $textarea; ?></textarea>
</p>
This code is simply adding 3 fields to the widget. The first one is the widget title, the second a text field, and the last one is a textarea. Let’s see now how to save and update each field value with the update() function.

3 –  The update() function

The update() function is really simple. As WordPress core developers added a really powerful widgets API, we only need to add this code to update each field:
// update widget
function update($new_instance, $old_instance) {
      $instance = $old_instance;
      // Fields
      $instance['title'] = strip_tags($new_instance['title']);
      $instance['text'] = strip_tags($new_instance['text']);
      $instance['textarea'] = strip_tags($new_instance['textarea']);
     return $instance;
}
And tada! the magic appears! You don’t need more code to save values, isn’t it awesome?

4 –  The widget() function

The widget() function is the one that will output the content on the website. It’s what your visitors will see. This function can be customized to include CSS classes, and specific tags to match perfectly your theme display. Here is the code (please not that this code can be modified easily to fit your needs):
// display widget
function widget($args, $instance) {
   extract( $args );
   // these are the widget options
   $title = apply_filters('widget_title', $instance['title']);
   $text = $instance['text'];
   $textarea = $instance['textarea'];
   echo $before_widget;
   // Display the widget
   echo '<div class="widget-text wp_widget_plugin_box">';

   // Check if title is set
   if ( $title ) {
      echo $before_title . $title . $after_title;
   }

   // Check if text is set
   if( $text ) {
      echo '<p class="wp_widget_plugin_text">'.$text.'</p>';
   }
   // Check if textarea is set
   if( $textarea ) {
     echo '<p class="wp_widget_plugin_textarea">'.$textarea.'</p>';
   }
   echo '</div>';
   echo $after_widget;
}
This code isn’t complex, all you have to remember is to to check if a variable is set, if you don’t and if you want to print it, you’ll get an error message.

Conclusion

As you saw, creating a WordPress widget isn’t complicated. We saw how to create simple inputs fields, and in my next post I’ll show you how to add more complex field types. But now i hope you enjoyed this first tutorial about widgets. I’ll be more than happy to hear from you in the comments section!

Tùy chỉnh Widget với Checkbox

http://wordpress.stackexchange.com/questions/112266/how-to-include-checkbox-in-widget-backend-form

Wordpress Widget Tùy chỉnh Checkbox

Set Widget settings to "checked by default"

If you want to set up default values for your Wordpress Widget, you have to manage some steps in your PHP code. It's more easier to set up with false or no checked options, but there are ways to handle true-presets.
Give a little notice to the Widget initializing, update, UI, hooks, etc. and your Wordpress Widget will get a true or checked option at start-up and after installing process.

The constructor

Setting up the Widget with the constructor. This is the first function which will be called after registration the Widget. Each time you set it up to a Widget menu the constructor function is called.
The constructor will allow us to set up the Widget default settings.

We'll call the overloaded WP_Widget function in the constructor with the default values in a $control_ops array.


class CategoryPosts extends WP_Widget {

 function __construct() {
  $widget_ops = array( 'classname' => 'cat-post-widget', 'description' => 'List posts' );
  $control_ops = array( 'show_title' => true );
  parent::__construct( 'category-posts', 'Category Posts Widget', $widget_ops, $control_ops );
 } // end __construct

Use the option imidatelly after set-up the Widget on the page

The Widget works in widget() function. Place all code here which should out-putted, displayed and make logical things. Here it means to show the Widget title if the Checkbox is checked or not hide it, if not.

Use the $instance array.


 function widget( $args, $instance ) {
  ...
  if( isset ( $instance["show_title"] ) && $instance["show_title"] ) {
   echo $before_title;
   echo $instance["title"];
   echo $after_title;
  }
  ...
 } // end widget

Making sure our widget is updated and saved

After using we have to take our Widget settings and save it. Its a pretty simple code for updating the Widget to use the new selected value.

Use the arrays $new_instance und $old_instance to save your Widget settings.


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

Use default values in the configuration UI with wp_parse_args

Configure the registration Widget UI setting.
For this use the wp_parse_args() function which overrids not setted values in the $instance array with default values.

Pre-set the option a second time for the form/UI. It's important just as the constructor pre-setting.


 function form( $instance ) {
  $defaults = array( 'show_title' => __( true ) );
  $instance = wp_parse_args( ( array ) $instance, $defaults );
  ...

Controls and settings for the Widget configuration UI

For the form use a checkbox, which allow the user to select a true/false option.

Create a checkbox and close the PHP code.


  ...
  <p>
   <label for="<?php echo $this->get_field_id("show_title"); ?>">
    <input type="checkbox" class="checkbox" 
     id="<?php echo $this->get_field_id("show_title"); ?>" 
     name="<?php echo $this->get_field_name("show_title"); ?>"
     <?php checked( (bool) $instance["show_title"], true ); ?> />
    <?php _e( 'Show title' ); ?>
   </label>
  </p>
 <?php
 } // end form
} // end CategoryPosts extends WP_Widget
?>

Lấy nội dung page hiển thị ra ngoài trang chủ wordpress

<?php
$namhp_page = new WP_Query(array(
'post_type'=>'page',
'page_id'=> 40));
?>
<?php while ($namhp_page->have_posts()) : $namhp_page->the_post(); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endwhile ; wp_reset_query() ;?>