Last week I explained how I shared my WordPress content with Hugo. Now, that was all well and good, but there is an obvious way I can do this when I don’t have a tool that understands dynamic content?

I’ve got PHP so the answer is “You bet your britches, baby!”

The First Version

If you just want to grab the URL and output the post content, you can do this:

$curl = curl_init();
curl_setopt_array( $curl, array(
	CURLOPT_FAILONERROR    => true,
	CURLOPT_CONNECTTIMEOUT => 30,
	CURLOPT_TIMEOUT        => 60,
	CURLOPT_FOLLOWLOCATION => false,
	CURLOPT_MAXREDIRS      => 3,
	CURLOPT_SSL_VERIFYPEER => false,
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_URL            => 'https://example.com/wp-json/wp/v2/pages/12345'
));

$result = curl_exec( $curln);
curl_close( $curl );

$obj = json_decode( $result );

echo $obj->content->rendered;

Now this does work, and it works well, but it’s a little basic and it doesn’t really sanitize things. Plus I would be placing this code in multiple files per site (not everyone themes as nicely as WordPress, ladies and gentlemen). So I wanted to write something that was more easily repeatable.

The Advanced Code

With that in mind, I whipped up a PHP file that checks and validates the URL, makes sure it’s a wp-json URL, makes sure it’s JSON, and then spits out the post content.

<?php

/* This code shows the content of a WP post or page.
 *
 * To use, pass the variable ?url=FOO
 *
 */

if (!$_GET || !$_GET["url"]) return;

include_once( "StrictUrlValidator.php" );

$this_url = (string) filter_var( $_GET['url'], FILTER_SANITIZE_URL );

if (strpos( $this_url, 'wp-json') == FALSE ) return;

function do_curl ( $url ) {
	$curl = curl_init();

	curl_setopt_array( $curl, array(
		CURLOPT_FAILONERROR    => true,
		CURLOPT_CONNECTTIMEOUT => 30,
		CURLOPT_TIMEOUT        => 60,
		CURLOPT_FOLLOWLOCATION => false,
		CURLOPT_MAXREDIRS      => 3,
		CURLOPT_SSL_VERIFYPEER => false,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_URL            => $url
	) );

	return curl_exec( $curl );
	curl_close( $curl );
}

if ( StrictUrlValidator::validate( $this_url, true, true ) === false ) {
	$return = "ERROR: Bad URL";
} else {
	$obj = json_decode( do_curl ( $this_url ) );

	if ( json_last_error() === JSON_ERROR_NONE ) {
		$return = $obj->content->rendered;
	} else {
		$return = "ERROR: Bad JSON";
	}
}

echo $return;

You can see I have some complex and some basic checks in there. The URL validation is done via a PHP Library called StrictUrlValidator. If I was using WordPress, I’d have access to esc_url() and other nifty things, but since I’m running this out in the wild, I make do with what I have.

Reader Interactions

%d bloggers like this: