If you're like me, sometimes you want to be able to reference WordPress functions in a page which does not exist in the CMS. This way, it remains backend-specific and cannot be accidentally deleted by the client.
This is actually simple to do just by including the wp-blog-header.php file using a PHP require().
Here's an example that uses a query string to generate Facebook Open Graph (OG) data for any post.
Take the example of a link like http://example.com/yourfilename.php?1 where 1 is the ID of a post we want to generate OG data for:
Now in the contents of yourfilename.php which, for our convenience, is located in the root WordPress directory:
<?php
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
$uri = $_SERVER['REQUEST_URI'];
$pieces = explode("?", $uri);
$post_id = intval( $pieces[1] );
// og:title
$title = get_the_title($post_id);
// og:description
$post = get_post($post_id);
$descr = $post->post_excerpt;
// og:image
$img_data_array = get_attached_media('image', $post_id);
$img_src = null;
$img_count = 0;
foreach ( $img_data_array as $img_data ) {
if ( $img_count > 0 ) {
break;
} else {
++$img_count;
$img_src = $img_data->guid;
}
} // end og:image
?>
<!DOCTYPE HTML>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=yes" />
<meta property="og:title" content="<?php echo $title; ?>" />
<meta property="og:description" content="<?php echo $descr; ?>" />
<meta property="og:locale" content="en_US" />
<meta property="og:type" content="website" />
<meta property="og:url" content="<?php echo site_url().'/your_redirect_path'.$post_id; ?>" />
<meta property="og:image" content="<?php echo $img_src; ?>" />
<meta property="og:site_name" content="Your Title" />
</html>
There you have it: generated sharing models for any post using the post's actual image, excerpt and title!
We could have created a special template and edited the permalink structure to do this, but since it's only needed for one page and because we don't want the client to delete it from within the CMS, this seemed like the cleaner option.
EDIT 2017:
Please note that this approach is now deprecated
For WordPress installations from 2016+ please see How can I add a PHP page to WordPress? for extra parameters to include before outputting your page data to the browser.