How to add widget search into the WordPress Widgets page

Quick Preview

To add the search follow below steps:


Step 1: Add search input field in WordPress backend

  • Open file /wp-admin/widgets.php
  • Goto line 429
  • Press enter key and add below code:
<div class="widgets-search">
	<input type="search" id="widgets-search-input" class="regular-text" placeholder="<?php _e('Search widgets...'); ?>">
</div>

Step 2: Add CSS for the input field

  • Open file /wp-admin/css/widgets.css
  • Goto line 775
  • Press enter key and add below code:
/* =Widget Search
-------------------------------------------------------------- */
#widgets-search-input {
	margin: 0 0 .2em 0;
	width: 100%;
	font-size: 16px;
	font-weight: 300;
	line-height: 1.5;
	border-width: 1px;
	border-style: solid;
	border-color: #ddd;
}


.show-widget {
    display: block;
}

.hide-widget {
    display: none;
}

Step 3: Add JS for the search widgets

  • Open file /wp-admin/js/widgets.js
  • Goto line 504
  • Press enter key and add below code:
/*
 * Use feature detection to determine whether inputs should use
 * the `keyup` or `input` event. Input is preferred but lacks support
 * in legacy browsers. See changeset 34078, see also ticket #26600#comment:59
 */
if ( 'oninput' in document.createElement( 'input' ) ) {
	inputEvent = 'input';
} else {
	inputEvent = 'keyup';
}

$( '#widgets-search-input' ).on( inputEvent, function() {

	var search_term   = $('#widgets-search-input').val() || '',
		parent        = $('#widgets-left'),
		widgets       = parent.find('.widget'),
		widget_titles = parent.find('.widget-title');

	if( search_term.length ) {

		// Hide all widgets. Because, Below we show those widgets
		// which have search term in the widget title.
		widgets.addClass('hide-widget').removeClass('show-widget');

		// Search widget and ONLY show these widgets which "contain" the widget title.
		var rex = new RegExp( search_term, 'i');
        widget_titles.filter(function () {
			var widget_name = $.trim( $(this).text() ) || '';
        	return rex.test( widget_name );
        }).parents('.widget').removeClass('hide-widget').addClass('show-widget');

	} else {

		// Show all widgets.
		widgets.removeClass('hide-widget').addClass('show-widget');
	}
});

Great!

Or

Also, check below complete code snippet gist:

See how it widget search works in below video:


I have created a patch for the WordPress core. See https://core.trac.wordpress.org/ticket/47540

Get all posts which contain specific shortcode

While working on some project, I was stuck on one issue.

The issue was, User was multiple posts and he was use my shortcode on some of them.

And I was trying to figure out which are the posts which content have my shortcode.


The answer is in my question. To do this I need to search the shortcode from all the post content.

To achieve this I have used SELECT query. E.g.

My shortcode was something like myshortcode (Not exactly this shortcode, I have use this shortcode for example purpose.)

Example 1: Search shortcode myshortcodein all the posts. (Including posts, pages, custom post types)

global $wpdb;
$ids = $wpdb->get_row("SELECT ID FROM {$wpdb->postmeta} WHERE meta_value LIKE '%myshortcode%'", ARRAY_A);

// print_r( $ids ); // Print all the IDs.

Above SELECT query return the array of IDs of all the posts, pages, custom post types which post content contain myshortcode.


Example 2: Search shortcode myshortcode ONLY in PAGES.

global $wpdb;
$ids = $wpdb->get_row("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%[myshortcode AND post_type='page'", ARRAY_A);

// print_r( $ids ); // Print all the IDs.

Create the post on wordpress.com site using oAuth and Rest API

Working on Rest API and OAuth is very interesting.

WordPress merged Rest API support into the core in WordPress 4.7 “Vaughan” check out the Rest API Merge Proposal.

In this post, I’m creating the post on my site https://maheshwaghmare.wordpress.com/ though rest API and OAuth.

Let’s Try it Step by Step

Step 1:

Create new app wordpress.com app from https://developer.wordpress.com/apps/new/

OR

Do you already have an app then select existing app from https://developer.wordpress.com/apps/

Step 2:

Copy below code and add your app authentication details. After adding details you get and auth key.

// Step: 1  Add authentication details to get auth key.
$auth_args = array(
	'username'      => '',
	'password'      => '',
	'client_id'     => '',
	'client_secret' => '',
	'grant_type'    => 'password', // Keep this as it is.
);
$access_key = get_access_key( $auth_args );

Note: Keep grant_type as password. Its required!

  • username – Your website username.
  • password – Your website password.
  • client_id – Your App client ID.
  • client_id – Your App client ID.

Step 3:

Use below function which return the auth key from your given app details.

/**
 * Get Access Key.
 * 
 * @param  array $args 	Auth arguments.
 * @return mixed       	Auth response.
 */
function get_access_key( $args ) {

	// Access Token.
	$curl = curl_init( 'https://public-api.wordpress.com/oauth2/token' );
	curl_setopt( $curl, CURLOPT_POST, true );
	curl_setopt( $curl, CURLOPT_POSTFIELDS, $args );
	curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
	$auth = curl_exec( $curl );
	$auth = json_decode($auth);

	// Access Key.
	return $auth->access_token;
}

Step 4:

Add your new post details. Such as post title, post content etc. like below:

// Step: 2  Set post arguments and pass it create the post.
$post_args = array(
	'title'       => 'Hello APA World',
	'content'     => 'Hello. I am a test post. I was created by the API',
	'tags'        => 'tests',
	'post_status' => 'draft',
	'categories'  => 'API',
);

Step 5:

Now, Simply call a function and pass the Auth key and post arguments.

// Create a post with the access key.
create_post( $access_key, $post_args );

Step 6:

/**
 * Create post with access key.
 * 
 * @param  string $access_key 	Access key.
 * @param  array $post_args 	Post arguments.
 * @return mixed       			Post response.
 */
function create_post( $access_key, $post_args )
{
	$options  = array (
		'http' => array(
			'ignore_errors' => true,
			'method'        => 'POST',
			'header'        => array(
		    	0 => 'authorization: Bearer ' . $access_key,
		    	1 => 'Content-Type: application/x-www-form-urlencoded',
		  	),
		  	'content' => http_build_query( $post_args ),
		),
	);
	 
	$context  = stream_context_create( $options );
	$response = file_get_contents(
	    'https://public-api.wordpress.com/rest/v1/sites/YOURSITEID/posts/new/',
	    false,
	    $context
	);
	return json_decode( $response );
}

Here,

https://public-api.wordpress.com/rest/v1/sites/YOURSITEID/posts/new/

Replace YOURSITEID with your wordpress.com site ID.

To get it follow below quick simple steps:

  • Goto api console
  • Add string /me/sites and select method GET
  • Press Enter.

It’ll show all your sites from WordPress.com. Check the below screenshot for reference.


Step 7:

Yup! Its not a step.

That’s it. Your first post successfully created!

Use below Complete Code snippet.Try this and let me know in comments.

The complete code snippet to create a post on wordpress.com is below:

Conclusion

In above example you can create a post on wordpress.com with the help of get_access_key() and create_post() functions from above code snippet.

Note: use unique prefix for get_access_key and create_post() to avoid the conflict with existing function with same name.

Working with Rest API is pretty simple. Let’s try it and let me know in comments.

Get all posts by post meta key and meta value

Description

For some situations, we need to get all the posts which have specific meta key and meta value.

We can do it with the help of the WP_Query class.

Example

Note: I’m giving you an imaginary example just for a reference to understand, In which situation you can use below code snippet.

Suppose,

  • We have a custom post type properties.
  • We have 15 properties are published.
  • We have store the location of each property in meta key property-location
  • And, We want to get all the properties which meta key is property-location with meta value Pune.

Code Snippet

$query_args = array(
	'post_type'  => 'properties',
	'meta_query' => array(
	    array(
			'key'   => 'property-location',
			'value' => 'Pune',
	    ),
	)
);

$query = new WP_Query( $query_args );

Here,
post_type is our custom post type slug. In our example its properties.
key is meta key. In our example its property-location
value is meta value. In our example its Pune

Gist Snippet

You can use below complete gist code snippet for reference.
Note: In below code snippet you need to change the parameters as you need.


Here,
I have added some extra parameters to optimize the WordPress query.

  • fields with value ids which return ONLY array post IDs of all found items.
  • no_found_rows with value true which optimizes the query.
  • posts_per_page with value -1 to get all the posts. Default it return only 10 items.

Show all READY scheduled events OR READY corn jobs in WordPress

Description

By using the function wp_get_ready_cron_jobs() to get all the READY scheduled events OR READY corn jobs.

Note: Use below code snippet for ONLY debugging/development purpose.

Code Snippet

Output

Array
(
    [1551289036] => Array
        (
            [wp_import_astra_sites_cron] => Array
                (
                    [40cd750bba9870f18aada2478b24840a] => Array
                        (
                            [schedule] => wp_import_astra_sites_cron_interval
                            [args] => Array
                                (
                                )

                            [interval] => 300
                        )

                )

        )

)

Show all scheduled events OR corn jobs in WordPress

Description

By using the funciton wp_get_schedules () to get all the scheduled events OR corn jobs.

Note: Use below code snippet for ONLY debugging/development purpose.

Code Snippet

Output

Array
(
    [wp_import_astra_single_site_cron_interval] => Array
        (
            [interval] => 300
            [display] => Every 5 Minutes
        )

    [wp_import_astra_images_site_cron_interval] => Array
        (
            [interval] => 300
            [display] => Every 5 Minutes
        )

    [wp_import_astra_site_terms_cron_interval] => Array
        (
            [interval] => 300
            [display] => Every 5 Minutes
        )

    [wp_import_astra_sites_cron_interval] => Array
        (
            [interval] => 300
            [display] => Every 5 Minutes
        )

    [hourly] => Array
        (
            [interval] => 3600
            [display] => Once Hourly
        )

    [twicedaily] => Array
        (
            [interval] => 43200
            [display] => Twice Daily
        )

    [daily] => Array
        (
            [interval] => 86400
            [display] => Once Daily
        )

)

PHP Date and Time format with examples and descriptions

Date Examples:

OutputFormatExample
15/02/19d/m/ydate( ‘d/m/y’ )
15-Feb-2019d-M-Ydate( ‘d-M-Y’ )
15 February 2019d F Ydate( ‘d F Y’ )
15th February 2019dS F Ydate( ‘dS F Y’ )
Feb, 15th 2019M, dS Ydate( ‘M, dS Y’ )

Time 12 hrs Examples:

OutputFormatExample
05:36 pmh:i adate( ‘h:i a’ )
05:36 PMh:i Adate( ‘h:i A’ )
05:36:18 pmh:i:s adate( ‘h:i:s a’ )
05:36:18 PMh:i:s Adate( ‘h:i:s A’ )

Time 24 hrs Examples:

OutputFormatExample
17:36 pmH:i adate( ‘H:i a’ )
17:36 PMH:i Adate( ‘H:i A’ )
17:36:18 pmH:i:s adate( ‘H:i:s a’ )
17:36:18 PMH:i:s Adate( ‘H:i:s A’ )

Date & Time Examples:

OutputFormatExample
15-02-2019 05:36:18 pmd-m-Y h:i:s adate( ‘d-m-Y h:i:s a’ )
15-Feb-2019 05:36:18 pmd-M-Y h:i:s adate( ‘d-M-Y h:i:s a’ )
15 February 2019 05:36 pmd F Y h:i adate( ‘d F Y h:i a’ )

All format with example and description:

FormatExampleDescription
d15d – The day of the month (from 01 to 31)
DFriD – A textual representation of a day (three letters)
j15j – The day of the month without leading zeros (1 to 31)
lFridayl (lowercase ‘L’) – A full textual representation of a day
N5N – The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
SthS – The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j)
w5w – A numeric representation of the day (0 for Sunday, 6 for Saturday)
z45z – The day of the year (from 0 through 365)
W07W – The ISO-8601 week number of year (weeks starting on Monday)
FFebruaryF – A full textual representation of a month (January through December)
m02m – A numeric representation of a month (from 01 to 12)
MFebM – A short textual representation of a month (three letters)
n2n – A numeric representation of a month, without leading zeros (1 to 12)
t28t – The number of days in the given month
L0L – Whether it’s a leap year (1 if it is a leap year, 0 otherwise)
o2019o – The ISO-8601 year number
Y2019Y – A four digit representation of a year
y19y – A two digit representation of a year
apma – Lowercase am or pm
APMA – Uppercase AM or PM
B775B – Swatch Internet time (000 to 999)
g5g – 12-hour format of an hour (1 to 12)
G17G – 24-hour format of an hour (0 to 23)
h05h – 12-hour format of an hour (01 to 12)
H17H – 24-hour format of an hour (00 to 23)
i36i – Minutes with leading zeros (00 to 59)
s18s – Seconds, with leading zeros (00 to 59)
u000000u – Microseconds (added in PHP 5.2.2)
eUTCe – The timezone identifier (Examples: UTC, GMT, Atlantic/Azores)
I0I (capital i) – Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise)
O+0000O – Difference to Greenwich time (GMT) in hours (Example: +0100)
P+00:00P – Difference to Greenwich time (GMT) in hours:minutes (added in PHP 5.1.3)
TUTCT – Timezone abbreviations (Examples: EST, MDT)
Z0Z – Timezone offset in seconds. The offset for timezones west of UTC is negative (-43200 to 50400)
c2019-02-15T17:36:18+00:00c – The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00)
rFri, 15 Feb 2019 17:36:18 +0000r – The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
U1550252178U – The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)