Create WordPress widget template from scratch

I’ve save down the most basic widget code for WordPress, you can copy this to your plugin and modify it to start your first widget. You can save time on this tutorial to help you create wordpress widget from scratch.

<?php

class example_widget extends WP_Widget {
    function __construct() {
        parent::__construct(false, $name = 'Example Widget');	
    }
 
 	/** @see WP_Widget::widget -- do not rename this */
    function widget($args, $instance) {	
        extract( $args );
        $title 		= apply_filters('widget_title', $instance['title']);
        $message 	= $instance['message'];
        ?>
		<?php echo $before_widget; ?>
			<?php if ( $title )
			echo $before_title . $title . $after_title; ?>
			<ul>
				<li><?php echo $message; ?></li>
			</ul>
			<?php echo $after_widget; ?>
        <?php
    }
 
    /** @see WP_Widget::update -- do not rename this */
    function update($new_instance, $old_instance) {		
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['message'] = strip_tags($new_instance['message']);
        return $instance;
    }
 
    /** @see WP_Widget::form -- do not rename this */
    function form($instance) {	
        $title 		= esc_attr($instance['title']);
        $message	= esc_attr($instance['message']);
        ?>
         <p>
          <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label> 
          <input class="" 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('message'); ?>"><?php _e('Simple Message'); ?></label> 
          <input class="" id="<?php echo $this->get_field_id('message'); ?>" name="<?php echo $this->get_field_name('message'); ?>" type="text" value="<?php echo $message; ?>" />
        </p>
        <?php 
    }
 
 
} // end class example_widget
add_action('widgets_init', create_function('', 'return register_widget("example_widget");'));
?>

lazy-result.js ReferenceError: Promise is not defined

node_modules/postcss/lib/lazy-result.js:157
        this.processing = new Promise(function (resolve, reject) {
                              ^
ReferenceError: Promise is not defined

When I install the FoundationPress, after I run gulp build I saw this message,
this is because the node version problem.

the have mention in this post
https://github.com/postcss/postcss-nested/issues/30

Solution

vim node_modules/postcss/lib/lazy-result.js

Put this to the first line of the file lazy-result.js

require('es6-promise').polyfill();

Save.

Then install

npm install es6-promise

Then build again

[[email protected]]# gulp build
[18:14:07] Starting 'clean'...
[18:14:07] Starting 'clean:javascript'...
[18:14:07] Starting 'clean:css'...
[18:14:07] Finished 'clean:javascript' after 4.56 ms
[18:14:07] Finished 'clean:css' after 2.98 ms
[18:14:07] Finished 'clean' after 6.38 ms
[18:14:07] Starting 'build'...
[18:14:07] Starting 'copy'...
[18:14:07] Finished 'copy' after 103 ms
[18:14:07] Starting 'sass'...
[18:14:08] Starting 'javascript'...
[18:14:08] Starting 'lint'...
[18:14:10] Finished 'lint' after 1.53 s
[18:14:10] Finished 'sass' after 2.58 s
[18:14:14] Finished 'javascript' after 6.12 s
[18:14:14] Finished 'build' after 6.78 s

Success !

Connect to Jetpack using behind varnish and nginx

Normally if you use varnish or other reverse proxy, you may use other port in wordpress. So you are not able to connect to Jetpack, because to connect Jetpack, you must have port 80 to authorize.

It may display the error like this from your Jetpack debugger

SELF:
	Array
(
    [headers] => Array
        (
            [server] => nginx
            [date] => Sat, 23 Aug 2014 00:57:12 GMT
            [content-type] => text/plain;charset=utf-8
            [connection] => close
            [x-pingback] => https://jetpack.wordpress.com/xmlrpc.php
            [expires] => Wed, 11 Jan 1984 05:00:00 GMT
            [cache-control] => no-cache, must-revalidate, max-age=60
            [pragma] => no-cache
            [x-hacker] => Jetpack Test
        )

    [body] => {"error":"Communication error","error_description":"We were unable to make an XML-RPC request to your website. Please make sure that XML-RPC is turned on and that Jetpack is installed, activated and connected with your WordPress.com account. If the error persists, try disconnecting and connecting Jetpack again."}
    [response] => Array
        (
             => 400
            [message] => Bad Request
        )

    [cookies] => Array
        (
        )

    [filename] => 
)

because of the $_SERVER['SERVER_PORT'] is not equal to value 80;
But we can cheat the Jetpack by add this to wp-config.php

$_SERVER['SERVER_PORT'] = 80;

Delete expired _transient in wordpress to optimize the database

If you separate your database to another server, and if the wp_options table is going bigger to 2MB, then it will slow down your query time, because WordPress like to query all the data from the table wp_options always.

You have to make the table smaller size to speed up the query.

I always clean up those useless _transient from the database, it could save you mostly 1MB

DELETE FROM `wp_options` WHERE `option_name` LIKE ('%\_transient\_%')

How to Setup Temporary WordPress Staging Site

I’m going to Setup Temporary WordPress Staging Site using same MySQL database. It is very useful for you to develop themes or plugin without affect to your current running sites, and you need to use real data to test it out.

Prepare your contents

Copy all your current contents from

/var/www/juzhax.com

to

/var/www/dev.juzhax.com

Set a domain and Point your Apache or Nginx to

Modify WordPress file

After that edit the file in wordpress

/var/www/dev.juzhax.com/wp-includeds/options.php

Inside the function get_option

Put this code, save it.

Put the codes

if ($option == "siteurl" || $option == "home") {
  return "http://dev.juzhax.com";
}

How to remove ver from js and css in WordPress ?

Remove the ver=date behind the JS and CSS in wordpress.

// Load in any own plugin
function juz_remove_wp_ver_css_js( $src ) {
    if ( strpos( $src, 'ver=' ) )
        $src = remove_query_arg( 'ver', $src );
    return $src;
}
add_filter( 'style_loader_src', 'juz_remove_wp_ver_css_js', 9999 );
add_filter( 'script_loader_src', 'juz_remove_wp_ver_css_js', 9999 );

Query WordPress Jetpack Stats using API and return as CSV

http://stats.wordpress.com/csv.php?api_key=123456789abc&blog_id=56174071&end=2013-12-31&day=500&limit=-1

Error: api_key is a required parameter.

Required parameters: api_key, blog_id or blog_uri.
Optional parameters: table, post_id, end, days, limit, summarize.

Parameters:
api_key     String    A secret unique to your WordPress.com user account.
blog_id     Integer   The number that identifies your blog. Find it in other stats URLs.
blog_uri    String    The full URL to the root directory of your blog. Including the full path.
table       String    One of views, postviews, referrers, referrers_grouped, searchterms, clicks, videoplays.
post_id     Integer   For use with postviews table. Also accepts a comma-separated list of integers.
end         String    The last day of the desired time frame. Format is 'Y-m-d' (e.g. 2007-05-01) and default is UTC date.
days        Integer   The length of the desired time frame. Default is 30. "-1" means unlimited.
period      String    For use with views table and the 'days' parameter. The desired time period grouping. 'week' or 'month'
                      Use 'days' as the number of results to return (e.g. '&period=week&days=12' to return 12 weeks)
limit       Integer   The maximum number of records to return. Default is 100. "-1" means unlimited. If days is -1, limit is capped at 500.
summarize   Flag      If present, summarizes all matching records.
format      String    The format the data is returned in, 'csv', 'xml' or 'json'. Default is 'csv'.

Non-working query example: ?api_key=123456789abc&blog_id=155&table=referrers&days=30&limit=-1&summarize

Result format is csv with one row per line and column names in first row.

Strings containing double quotes, commas, or "\n" are enclosed in double-quotes. Double-qoutes in strings are escaped by inserting another double-quote.
Example: "pet food" recipe
Becomes: """pet food"" recipe"

Developers, please cache the results for at least 180 seconds.

Remove ver version number for JS and CSS in WordPress

The varnish load so much of different version in my wordpress, so I would like to remove all the ver from the source.

    53.76 RxURL          /wp-content/themes/responsivepro/core/js/responsive-modernizr.js?ver=2.6.1
    51.22 RxURL          /wp-content/themes/responsivepro/core/js/responsive-scripts.js?ver=1.2.4
    16.12 RxURL          /wp-includes/js/jquery/jquery.js?ver=1.10.2
    15.70 RxURL          /wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1
    15.59 RxURL          /wp-content/themes/responsivepro/core/css/style.css?ver=1.9.3.4
    15.59 RxURL          /wp-content/themes/responsivepro/pro/lib/css/style.css?ver=1.0
    15.58 RxURL          /wp-content/plugins/RadControl/js/adclk.js?ver=2013-06-21
    15.56 RxURL          /wp-content/themes/responsivepro/style.css?ver=1.9.3.4
    15.56 RxURL          /wp-content/plugins/jetpack/modules/widgets/wid

Solution to solve

Add this into your functions.php in your theme.
You can access from Apperance –> Editor
Then you try to to put this code to update the file.

function _remove_script_version( $src ){
$parts = explode( '?', $src );
return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );