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.

Git vs SVN commands

We use Git and SVN for managing projects.

I personally work on Github, GitLab and BitBucket. I’m more familiar with Git commands.

WordPress itself use the SVN for hosting plugins and themes. I have created a WordPress Theme and Plugins. But, I personally not use SVN though command line.

I personally use Tortoise SVN for managing my theme and plugins. It provides a GUI (Graphic User Interface) which allow working on SVN with a very easy way. Read more about Tortoise SVN.

I was always querying about,

  1. How to work on SVN though command line?
  2. Which are the basic SVN commands like Git?
  3. What is the difference between Git and SVN commands?
  4. etc.

I’ll create an article on all the above questions which I have tried to resolve soon.

For now, I have created a table of Git vs SVN commands. You can also check below the table of Git vs SVN commands for reference.

Description GIT Command SVN Command
Copy a repository git clone svn checkout
Record changes to file history git commit svn commit
View commit details git show svn cat
Confirm status git status svn status
Check differences git diff svn diff
Check log git log svn log
Addition git add svn add
Move git mv svn mv
Delete git rm svn rm
Cancel change git checkout svn revert1
Cancel change git reset svn revert1
Make a branch git branch svn copy2
Switch branch git checkout svn switch
Merge git merge svn merge
Create a tag git tag svn copy2
Update git pull svn update
Update git fetch svn update
It is reflected on the remote git push svn commit
Ignore file list .gitignore .svnignore

 

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
        )

)

Get latest stable Plugin or Theme download zip URL from wp.org

Plugin Download URL

You can add a download button on your website with the link of latest plugin zip. So, Your users always get the latest zip of your plugin which is hosted on wp.org.

Stable plugin download zip URL is:

https://downloads.wordpress.org/plugin/{plugin-slug}.latest-stable.zip

Note: You need to use the plugin slug for {plugin-slug}.

How to find the plugin slug?

Visit any WordPress plugin page.

E.g. If you visit the plugin page Sample Data.
This page URL is https://wordpress.org/plugins/sample-data/

So, Plugin slug is sample-data
And its latest plugin download link is:
https://downloads.wordpress.org/plugin/sample-data.latest-stable.zip

Note: Plugin name and plugin slug is not always the same.

Another example, If you visit the plugin page Bulk Clean.
This page URL is https://wordpress.org/plugins/easy-clean/

So, Plugin slug is easy-clean
And its latest plugin download link is:
https://downloads.wordpress.org/plugin/easy-clean.latest-stable.zip

Some more plugin examples:

  1. Contact Form 7
    https://downloads.wordpress.org/plugin/contact-form-7.latest-stable.zip
  2. Bulk Clean
    https://downloads.wordpress.org/plugin/easy-clean.latest-stable.zip
  3. Copy Anything to Clipboard
    https://downloads.wordpress.org/plugin/copy-the-code.latest-stable.zip
  4. Free Images
    https://downloads.wordpress.org/plugin/free-images.latest-stable.zip
  5. Sample Data
    https://downloads.wordpress.org/plugin/sample-data.latest-stable.zip
  6. Site Reset
    https://downloads.wordpress.org/plugin/site-reset.latest-stable.zip

Theme Download URL

Same like a plugin, You can add a download button on your website with the link of your latest theme zip. So, Your users always get the latest zip of your theme which is hosted on wp.org.

Stable theme download zip URL is:

https://downloads.wordpress.org/theme/{theme-slug}.latest-stable.zip

Note: You need to use the theme slug for {theme-slug}.

How to find the theme slug?

Same as the plugin, Visit any WordPress theme.

If you visit the theme Bhari
This page URL is https://wordpress.org/themes/bhari/

So, Theme slug is bhari
https://downloads.wordpress.org/theme/bhari.latest-stable.zip

Some more theme examples:

  1. Bhari
    https://downloads.wordpress.org/theme/bhari.latest-stable.zip
  2. Twenty Twelve
    https://downloads.wordpress.org/theme/twentytwelve.latest-stable.zip
  3. Twenty Sixteen
    https://downloads.wordpress.org/theme/twentysixteen.latest-stable.zip
  4. Twenty Seventeen
    https://downloads.wordpress.org/theme/twentyseventeen.latest-stable.zip
  5. Twenty Nineteen
    https://downloads.wordpress.org/theme/twentynineteen.latest-stable.zip

Multisite Support for Site Metadata in WordPress 5.1

Quick Highlights:

  • WordPress multisite introduces a new database table wp_blogmeta to store metadata associated with sites. This allows for the storage of arbitrary site data relevant in a multisite/network context.

  • It provides an alternative to using options and can be retrieved from multiple sites in a more performant way—without calling  switch_to_blog(). Sites can now also be queried by their meta with parameters supported by WP_Meta_Query.

  • Note: A network update is required to install the new database table.

  • New API functions:
get_site_meta( $id, $meta_key, $single )
update_site_meta( $id, $meta_key, $meta_value, $prev_value )
add_site_meta( $id, $meta_key, $meta_value, $unique )
delete_site_meta( $id, $meta_key, $meta_value )

All of these functions are ONLY available in multisite, however they work similarly to other metadata wrapper functions, such as for posts, terms, comments and users. In addition to these functions, it is now possible to use the common meta query arguments when querying sites with  WP_Site_Query or its wrapper  get_sites().


Read more at https://make.wordpress.org/core/2019/01/28/multisite-support-for-site-metadata-in-5-1/