Share WordPress news on another web platform with JQuery

Wordpress Image templatingNot everyone knows that the wordpress news can be assigned to another platform written in any programming language where these two platforms (wordpress and other web-app) possess the same HTTP protocol.
In practice to achieve what we achieve a PHP script to be inserted via FTP to the root(public_html) of your wordpress blog.
As many web developers know one of my standard for also receive data using JavaScript is JSON. Therefore the idea is to make a JSON call with to wordpress blog which respond an JSON object and then programmer manipulate the JSON as you want.
For example in these statements filter all post that have the apache tag.

php script

require( dirname( __FILE__ ).'/wp-load.php' );
$tag_query = new gdv_Query( 'tag=' . 'apache' );
if( $tag_query->have_posts() ){
	$list_post=array();
	$counter_posts = 0;
	while ( $tag_query->have_posts() ) : $tag_query->the_post();
		$post = get_post();
		$data = new stdClass();
		$data->id=$post->ID;
		$data->url=html_entity_decode(get_permalink());
		$data->title=get_the_title();
		$date_format = 'Y.m.d G:i';
		$data->date_post=get_the_date( $date_format, $post->ID );
		$content = $post->post_content;
		$regex = '/src="([^"]*)"/';
		preg_match_all( $regex, $content, $matches );
		$matches = array_reverse($matches);
		$data->images=$matches[0];
		array_push($list_post,$data);
		$counter_posts+=1;
		if($counter_posts>=5)
			break;
	endwhile;
}
gdv_reset_postdata();
echo json_encode($list_post);

Comment rapidly these instructions:

  • require( dirname( __FILE__ ).’/wp-load.php’ );, load wordpres postdata.
  • $tag_query = new gdv_Query( ‘tag=’ . ‘apache’ );, filter posts with apache tag.
  • $list_post=array(), lists of posts.
  • Use the while to cycle the results and build the json object.
  • $post = get_post();, obtain post object.
  • $data = new stdClass();, single empty JSON object populated with: $post->ID, get_permalink(), get_the_title(), date(get_the_date( $date_format, $post->ID )) and images appropriately formatted.
  • gdv_reset_postdata(), close post_data.
  • echo json_encode($list_post);, print JSON Object.

Ok, now, in the wordpress blog should be given access to the cross-origin in the .htaccess. We can add these instructions.

<IfModule mod_headers.c>
   Header add Access-Control-Allow-Origin: <LINK_OTHER_PLATFORM_SAME_PROTOCOL>
</IfModule>

Now we can make the ajax call from web-app that requires the news of the wordpress blog.

$.getJSON('<SCRIPT_PHP_REALIZED>', function(data) {console.log(data);});
Share WordPress news on another web platform with JQuery ultima modidfica: 2016-10-09T18:32:09+02:00 da Gianluca Di Vincenzo