[Code] Excelsheet-wppost-restapi : Get Post Method

Icon

 

///////////////////////////////////////////////
/// START : GET Endpoint for WP REST API ///
///////////////////////////////////////////////

function get_post_callback($request) {
	
	$id = $request['id'];
	$cur_post_type = get_post_type($id);
	$builtin_types = ['post', 'page']; // builtin type

	if(in_array($cur_post_type, $builtin_types)) { //

		$post = get_post($id); 
		if ( ! $post ) {

			return new WP_Error('post_not_found', 'Post not found', array('status' => 404));

		} else {
			$data = array( 
				'ID' => $post->ID,
				'title' => $post->post_title,
				'content' => $post->post_content,
				//Add more files as needed.
			);
	
			// when send rendered content
			// $content_rendered = apply_filters( 'the_content', $post->post_content );
			// return $content_rendered;
	
			return new WP_REST_Response($data, 200);
		}
	} else { // assume kboard GUID passed

		$content = new KBContent();
		$content->initWithUID($id);

		if ( ! $content ) {

			return new WP_Error('post_not_found', 'Post not found', array('status' => 404));

		} else {
			$content->initWithUID($id);
			$rendered_content = apply_filters('the_content', $content->content); //apply rendered data, not editor data.
			$data = array(
				'ID' => $id,
				'title' => $content->title,
				'content' => $rendered_content
			);
	
			return new WP_REST_Response($data, 200);
		}
	}
}

function get_post_endpoint() {

	// register content get post method
	register_rest_route('/custom/v1', '/get_post/(?P<id>\d+)',
	array(
		'methods' => 'GET',
		'callback' => 'get_post_callback',
	));
}

add_action('rest_api_init', 'get_post_endpoint');

/////////////////////////////////////////////
/// END : GET Endpoint for WP REST API ///
/////////////////////////////////////////////

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

0
Would love your thoughts, please comment.x
()
x