Show group by alphabet posts with shortcode using WP_Query

Create an array of posts group by alphabet with WP_Query.

Use below to create the list of posts array with the group by alphabet.

Note: I have used post type. You can change this post type with your own. Also, you can modify the WP_Query parameters.

Now we can show the posts with the group by alphabet with a shortcode.

In below code we have created a shortcode prefix_alphabetic_posts to show the result in the post.

NOTE: Below short code is created only for demo purpose. So, Added inline CSS. You need to use wp_enqueue_scripts to enqueue your scripts.

How to capture website screenshot with CLI (Command Line Interface)

Introduction

Before writing about how to create a website screenshot of website with CLI command, I think, I need to share some background.

Recently, I was working on some project in which I need to set 1000+ web page screenshots and resize them and set as a featured featured image for the post.

In this article I’ll just share how to capture the website screenshot with the CLI command. I’ll create another article to share how I was resize the screenshot and set the featured images in future articles.


Research About the Right Tool

I have research about this and found some below tools.

After some research, I have tried all of the above tools and finally select the capture-website-cli because of it fulfill all my requirement and also create better screenshots.

Reasons to choose capture-website-cli:

  • We can set timeout while creating screenshot.
  • We can set delay while creating screenshot.
  • We can inject JS/CSS while creating screenshot.
  • We can create full page screenshot.
  • We can set emulate device.
  • We can set authentication
  • We can set PHP headers
  • much more..

capture-website-cli internally use the Puppeteer (Chrome).


How to Install capture-website-cli?

  • Create a folder e.g. capture-website-cli
  • Open terminal and execute command:
    npm install --global capture-website-cli

After executing above command it install the Google Chrome. It looks like below screenshot.

Install the capture-website-cli tool.

To check it install successfully type below command:
capture-website --help

After tying above command you can see like:

Confirm capture-website-cli is installed successfully.

How to use?

For testing I have use the website wordpress.org

Syntax:

capture-website {Website} {image}

Example 1:

capture-website https://wordpress.org/ wordpress.png

After executing above command the screenshot is generated like below:

Screenshot with capture-website-cli tool.

Example 2:

This is very interesting example. See below command.

I just want to highlight the Inject feature in which we can inject our custom CSS & JS while creating the screenshot.

capture-website https://wordpress.org/ wordpress-by-mahesh.png --script="script.js"

After executing the above command below screenshot is generated.

In above screenshot the string Mahesh Waghmare and This Screenshot is generated with 'capture-website-cli'. And also the string "Mahesh Waghmare" and this paragraph both are also injected with the JavaScript while creating https://wordpress.org/ web page screenshot.

Both are added though JS by injecting it with custom JS file while creating screenshot.

In above command the parameter --script is used. In which the script.js is set. And in this JS file I have write the below code:


Additional Parameters

Don’t forget try below parameters too. These are interesting.

  • --width Page width [default: 1280]
  • --height Page height [default: 800]
  • --type Image type: png|jpeg [default: png]
  • --quality Image quality: 0…1 (Only for JPEG) [default: 1]
  • --scale-factor Scale the webpage n times [default: 2]
  • --list-devices Output a list of supported devices to emulate
  • --emulate-device Capture as if it were captured on the given device
  • --full-page Capture the full scrollable page, not just the viewport
  • --no-default-background Make the default background transparent
  • --timeout Seconds before giving up trying to load the page. Specify 0 to disable. [default: 60]
  • --delay Seconds to wait after the page finished loading before capturing the screenshot [default: 0]
  • --wait-for-element Wait for a DOM element matching the CSS selector to appear in the page and to be visible before capturing the screenshot
  • --element Capture the DOM element matching the CSS selector. It will wait for the element to appear in the page and to be visible.
  • --hide-elements Hide DOM elements matching the CSS selector (Can be set multiple times)
  • --remove-elements Remove DOM elements matching the CSS selector (Can be set multiple times)
  • --click-element Click the DOM element matching the CSS selector
  • --scroll-to-element Scroll to the DOM element matching the CSS selector
  • --disable-animations Disable CSS animations and transitions [default: false]
  • --module Inject a JavaScript module into the page. Can be inline code, absolute URL, and local file path with .js extension. (Can be set multiple times)
  • --script Same as --module, but instead injects the code as a classic script
  • --style Inject CSS styles into the page. Can be inline code, absolute URL, and local file path with .css extension. (Can be set multiple times)
  • --header Set a custom HTTP header (Can be set multiple times)
  • --user-agent Set the user agent
  • --cookie Set a cookie (Can be set multiple times)
  • --authentication Credentials for HTTP authentication
  • --debug Show the browser window to see what it’s doing
  • --launch-options Puppeteer launch options as JSON
  • --overwrite Overwrite the destination file if it exists

Hope you enjoy this article. Try it yourself and let me know for any question. Some useful link:

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"&gt;
	<input type="search" id="widgets-search-input" class="regular-text" placeholder="<?php _e('Search widgets...'); ?&gt;"&gt;
</div&gt;

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

Most of the times we need to get all all custom fields of all the posts. We can get it with the help of the WP_Query class. Lets check it with simple example.

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
                        )

                )

        )

)