Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API call in amp pages when page load #89

Open
jeenamanuel opened this issue Aug 23, 2017 · 3 comments
Open

API call in amp pages when page load #89

jeenamanuel opened this issue Aug 23, 2017 · 3 comments

Comments

@jeenamanuel
Copy link

How can i make an api call in my amp page. api response is in json format

@grupie001
Copy link

I think I am looking for something similar. I would like to connect this "sample" to my wordpress api and useless WP just as headless Backend and this "sample" as front. Any suggestion how to do it?

@nisargrthakkar
Copy link

Yes, I am looking for the same. Rest API call in AMP page.

@westonruter
Copy link
Member

Do you mean requesting data from the WordPress REST API? If using the official AMP plugin for WordPress, the necessary CORS headers are added automatically. The headers are added automatically by AMP_HTTP::send_cors_headers() whenever the request includes the __amp_source_origin query param, which AMP adds automatically. So as long as WordPress is handling the fetch request, then the necessary CORS headers should all be supplied automatically.

So you just use the rest_url() that WordPress provides. For example, here is a shortcode that shows the latest posts:

add_shortcode(
	'amp_latest_posts',
	function() {
		$endpoint = rest_url( 'wp/v2/posts' );

		/*
		 * Enqueue scripts for when shortcode is used on non-AMP pages. These are unnecessary on AMP pages because the
		 * post-processor will automatically add them when it encounters <amp-list>.
		 */
		wp_enqueue_script( 'amp-list' );
		wp_enqueue_script( 'amp-mustache' );

		ob_start();
		?>
		<amp-list src="<?php echo esc_url( $endpoint ); ?>" items="." layout="fixed-height" height="300" width="auto">
			<template type="amp-mustache">
				<div>
					<a href="{{link}}">{{title.rendered}}</a>
				</div>
			</template>
		</amp-list>
		<?php
		return ob_get_clean();
	}
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants