WordPress Rest API: List Blog Posts Via Rest

  • Post author:
  • Post comments:0 Comments
  • Post last modified:September 26, 2021
WordPress Rest API

The below code will help you to list out blog posts from the external WordPress Site with the help of Rest API. Just copy the code and paste it to the functions.php file. This will create the shortcode named [qlc_list_posts_via_rest]. So paste the code where you want to display the posts.

And make sure to change the URL in line 7 to your destination site.

function list_posts_via_rest() {

	// Initialize variable.
	$allposts = '';
	
	// Enter the name of your blog here followed by /wp-json/wp/v2/posts and add filters like this one that limits the result to 2 posts.
	$response = wp_remote_get( 'https://quicklearncode.com/wp-json/wp/v2/posts' );

	// Exit if error.
	if ( is_wp_error( $response ) ) {
		return;
	}

	// Get the body.
	$posts = json_decode( wp_remote_retrieve_body( $response ) );

	// Exit if nothing is returned.
	if ( empty( $posts ) ) {
		return;
	}

	// If there are posts.
	if ( ! empty( $posts ) ) {

		// For each post.
		foreach ( $posts as $post ) {

			// Use print_r($post); to get the details of the post and all available fields
			// Format the date.
			$fordate = date( 'n/j/Y', strtotime( $post->modified ) );

			// Show a linked title and post date.
			$allposts .= '<a href="' . esc_url( $post->link ) . '" target=\"_blank\">' . esc_html( $post->title->rendered ) . '</a>  ' . esc_html( $fordate ) . '<br />';
		}
		
		return $allposts;
	}

}
// Register as a shortcode to be used on the site.
add_shortcode( 'qlc_list_posts_via_rest', 'list_posts_via_rest' );

Please comment below if you have any issues.

You may also refer to WordPress Rest API Documentation here.

You may also like https://www.quicklearncode.com/5-most-reliable-digital-marketing-strategies-for-small-business/

Leave a Reply