Return raw image proxy for wordpress plugin
I am trying to add a file to my wordpress plugin to return an image from a remote API using an authentication token stored in the plugin's configuration.
This is my current code:
?php
// Make sure we don't expose any info if called directly.
if (! function_exists('add_action')) {
echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
exit;
}
function hinews_get_image($id, $mimetype) {
$options = get_option('homeinfo_news_options');
$parm_token = '?access_token=' . $options['token'];
$base_url = 'https://myurl.com/';
$image_url = $base_url . $id . $parm_token;
header('Content-type: ' . $mimetype);
$image = file_get_contents($articles_url);
if ($image === FALSE) {
return 'Could not retrieve image.';
}
return $image;
}
hinews_get_image($_GET['id'], $_GET['mimetype']);
?
This file, currently called images.php
in my plugins folder, when referenced directly via URL will of course return the bail-out message, since it is not called from within a wordpress context.
I could not find any information on how to invoke this file correctly from within a shortcode-rendered page.
The invoking code is:
?php
/**
* Plugin Name: HOMEINFO News
* Plugin URI: https://www.homeinfo.de/
* Description: News articles provided by HOMEINFO.
* Version: 0.0.1
**/
// Make sure we don't expose any info if called directly.
if (! function_exists('add_action')) {
echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
exit;
}
include("settings.php");
add_shortcode('hinews', 'hinews_shortcode');
function hinews_shortcode(){
wp_enqueue_style('hinews.css', plugins_url('hinews.css', __FILE__));
wp_enqueue_script('hinews.js', plugins_url('hinews.js', __FILE__));
$options = get_option('homeinfo_news_options');
wp_localize_script('hinews.js', 'php_vars', $options);
$parm_token = '?access_token=' . $options['token'];
$base_url = 'https://myurl.com';
$articles_url = $base_url . $parm_token;
$response = file_get_contents($articles_url);
if ($response === FALSE) {
return 'Could not load data from API. Check your credentials.';
}
$news_list = json_decode($response);
$result = '';
foreach ($news_list as $news) {
$result .= 'h2' . $news-title . '/h2';
$result .= 'p' . $news-text . '/p';
$result .= 'br/';
foreach ($news-images as $image) {
$php_file = 'images.php';
$args = array('id' = $image-id, 'mimetype' = $image-mimetype);
$url_args = '?' . http_build_query($args);
$image_url = plugins_url($php_file . $url_args, __FILE__); # What to do here?
$result .= 'img src="' . $image_url . '" alt="' . $image-source . '"';
$result .= 'br/';
}
}
return $result;
}
?
Topic proxy urls plugin-development Wordpress
Category Web