wordpress featured image from external url without download - wordpress

i would like to use external pictures as featured image on wordpress.
either changing worpdress code. (adding a fetured image metabox accepting urls and do some modifications in order to display the featured image from url correctly)
or modifiying the plugin WP remote thumbnail, which set a featured image from an image url. it download the picture and create thumbnails in wordpress and set the featured image.
modifications:
* no download from the url, just use the url to display directly on the blog.
* remove wp-content/uploads from the url generated by wordpress to display featured image (only for external urls)
* no thumbnails creation.
thank you very much for reading
i know there is a lot of questions about this problem
but if we solve this question it could be useful for a lot of ppl.
here the code:
<?php
/*
Plugin Name: WP Remote Thumbnail
Plugin URI: http://magnigenie.com/wp-remote-thumbnail-set-external-images-featured-image/
Description: A small light weight plugin to set external/remote images as post thumbnail/featured image.
Version: 1.0
Author: Nirmal Kumar Ram
Author URI: http://magnigenie.com
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
?>
<?php
/**
* Initialize wprthumb on the post edit screen.
*/
function init_wprthumb() {
new wprthumb();
}
if ( is_admin() ) {
add_action( 'load-post.php', 'init_wprthumb' );
add_action( 'load-post-new.php', 'init_wprthumb' );
}
class wprthumb {
/**
* Hook into the appropriate actions when the wprthumb is constructed.
*/
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
add_action( 'save_post', array( $this, 'save' ) );
}
/**
* Adds the meta box container.
*/
public function add_meta_box( $post_type ) {
if ( post_type_supports( $post_type, 'thumbnail' )) {
add_meta_box(
'some_meta_box_name'
,'Remote Post Thumbnail'
,array( $this, 'render_meta_box_content' )
,$post_type
,'side'
,'default'
);
}
}
/**
* Save the meta when the post is saved.
*/
public function save( $post_id ) {
/*
* We need to verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times.
*/
// Check if our nonce is set.
if ( ! isset( $_POST['wprthumb_nonce'] ) )
return $post_id;
$nonce = $_POST['wprthumb_nonce'];
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce, 'wprthumb' ) )
return $post_id;
// If this is an autosave, our form has not been submitted,
// so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user's permissions.
if ( 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) )
return $post_id;
} else {
if ( ! current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
/* All good, its safe for us to save the data now. */
// Sanitize the user input.
$image = sanitize_text_field( $_POST['remote_thumb'] );
$upload_dir = wp_upload_dir();
//Get the remote image and save to uploads directory
$img_name = time().'_'.basename( $image );
$img = wp_remote_get( $image );
$img = wp_remote_retrieve_body( $img );
$fp = fopen( $upload_dir['path'].'/'.$img_name , 'w');
fwrite($fp, $img);
fclose($fp);
$wp_filetype = wp_check_filetype( $image , null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $image ),
'post_content' => '',
'post_status' => 'inherit'
);
//require for wp_generate_attachment_metadata which generates image related meta-data also creates thumbs
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_id = wp_insert_attachment( $attachment, $image, $post_id );
//Generate post thumbnail of different sizes.
$attach_data = wp_generate_attachment_metadata( $attach_id , $image );
wp_update_attachment_metadata( $attach_id, $attach_data );
//Set as featured image.
delete_post_meta( $post_id, '_thumbnail_id' );
add_post_meta( $post_id , '_thumbnail_id' , $attach_id, true);
}
/**
* Render Meta Box content.
*/
public function render_meta_box_content( $post ) {
// Add an nonce field so we can check for it later.
wp_nonce_field( 'wprthumb', 'wprthumb_nonce' );
// Display the form, using the current value.
echo '<label for="remote_thumb">';
_e( 'Enter remote image url', 'wprthumb' );
echo '</label> ';
echo '<input type="text" id="remote_thumb" name="remote_thumb" size="25" />';
}
}

I just found out that you can insert images from remote urls without having to first download them and then re-upload them. This works by default in Wordpress without any requirement to install any plugins.
Here's how:
Wherever you see UPLOAD FILES, click that - your file browser will appear where you'd expect you must choose a local file, BUT if you just paste the IMAGE URL into this box and hit OPEN or [ENTER] then Wordpress imports the image from the remote URL.
Click SELECT FILES to upload images from a remote URL
Paste the remote image URL into the place where you'd normally have the file name

I just find this plugin that seems to do what you need :
https://wordpress.org/plugins/external-featured-image

You can use the plugin Featured Image from URL (FIFU) for that.

Related

Custom Field created in add_meta_boxes reappearing itself again in the default Custom Metabox

I succeed in creating a metabox with custom field inside, and I restrict it to appear in a custom post type.
//define metabox
function product_info_en() {
add_meta_box( 'english_info', 'English Info', 'english_product_name_callback', array('product'), 'normal', 'high' );
}
//add to hook
add_action( 'add_meta_boxes', 'product_info_en' );
The code to display it in the product page:
// display in add product admin page
function english_product_name_callback( $post ) {
//ob_start();
$content = esc_attr( get_post_meta( get_the_ID(), 'product_desc_en', true ) );
//here goes the custom field
echo '<fieldset><div><label><b>English Product Name:</b></label><br/>';
echo '<input id="product_name_en" type="text" name="product_name_en" style="width:100%; margin:10px 0px"';
echo ' value="';
echo esc_attr( get_post_meta( get_the_ID(), 'product_desc_en', true ) );
echo '"></div></fieldset>';
//here goes the wp_editor
echo '<fieldset><div><label><b>English Product Content Info:</b></label><div><br/>';
echo '<div>';
wp_editor($content, 'product_desc_en', array(
'wpautop' => true,
'media_buttons' => true,
'textarea_rows' => 10
)
);
echo '</div></fieldset>';
}
Here goes the code that do the saving job:
//save
function enginfo_save_meta_box( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( $parent_id = wp_is_post_revision( $post_id ) ) {
$post_id = $parent_id;
}
$fields = [
'product_name_en',
];
foreach ( $fields as $field ) {
if ( array_key_exists( $field, $_POST ) ) {
update_post_meta( $post_id, $field, sanitize_text_field( $_POST[$field] ) );
}
}
update_post_meta( $post_id,'product_desc_en', wp_kses_post( $_POST['product_desc_en'] ) );
}
add_action( 'save_post', 'enginfo_save_meta_box' );
However, the custom created field that supposed to be going only into the newly created metabox, will always show up in the default "custom field". And this happens to all post type.
As shown below, What could possibly be the issue here?
To hide and not show your custom fields there in default box, please prefix your custom fields with underscore _ , so product_desc_en will become _product_des_en
I mean the names of your custom fields should be prefixed with underscore and WordPress default custom metabox will ignore them and not show in WordPress default GUI, but you can use and display them in your own custom metaboxes by calling with there new Underscore prefixed names.

How to fix 'Woocommerce Cart PDF' functions file to move pdf-link to checkout page instead of cart page

I'm using a plugin for wordpress-woocommerce called Woocommerce Cart PDF (https://wordpress.org/plugins/wc-cart-pdf/). It generates a pdf-link of the current cart, but is located on the cart page.
I have a combined cart and checkout page so the link does not appear on my website. I don't have the knowledge on how to edit the plugin files myself for it to appear on my cart page.
I've tried the wordpress plugin support forum for this specific plugin, but no answer.
/**
* Generates the PDF for download
*
* #return void
*/
function wc_cart_pdf_process_download() {
if( ! function_exists( 'WC' ) ) {
return;
}
if( ! isset( $_GET['cart-pdf'] ) ) {
return;
}
if( ! is_cart() || WC()->cart->is_empty() ) {
return;
}
if( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'cart-pdf' ) ) {
wc_add_notice( __( 'Invalid nonce. Unable to process PDF for download.', 'wc_cart_pdf' ), 'error' );
return;
}
$dompdf = new \Dompdf\Dompdf();
$content = $css = '';
$cart_table = wc_locate_template( 'cart-table.php', '/woocommerce/wc-cart-pdf/', __DIR__ . '/templates/' );
$css = wc_locate_template( 'pdf-styles.php', '/woocommerce/wc-cart-pdf/', __DIR__ . '/templates/' );
do_action( 'wc_cart_pdf_before_process' );
if( file_exists( $cart_table ) ) {
ob_start();
include $cart_table;
$content = ob_get_clean();
}
if( file_exists( $css ) ) {
ob_start();
include $css;
$css = apply_filters( 'woocommerce_email_styles', ob_get_clean() );
}
$dompdf->loadHtml( '<style>' . $css . '</style>' . $content );
$dompdf->setPaper( 'A4', 'portrait' );
$dompdf->render();
$dompdf->stream(
apply_filters( 'wc_cart_pdf_filename', 'WC_Cart-' . date( 'Ymd' ) . bin2hex( openssl_random_pseudo_bytes( 5 ) ) ) . '.pdf',
/**
* 'compress' => 1 or 0 - apply content stream compression, this is on (1) by default
* 'Attachment' => 1 or 0 - if 1, force the browser to open a download dialog, on (1) by default
*/
apply_filters( 'wc_cart_pdf_stream_options', array( 'compress' => 1, 'Attachment' => 1 ) )
);
exit;
}
add_action( 'template_redirect', 'wc_cart_pdf_process_download' );
if( ! function_exists( 'wc_cart_pdf_button' ) ) {
/**
* Renders the download cart as PDF button
*
* #return void
*/
function wc_cart_pdf_button() {
if( ! is_cart() || WC()->cart->is_empty() ) {
return;
}
?>
<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'cart-pdf' => '1' ), wc_get_cart_url() ), 'cart-pdf' ) );?>" class="cart-pdf-button button" target="_blank">
<?php esc_html_e( 'Download Cart as PDF', 'wc-cart-pdf' ); ?>
</a>
<?php
}
}
add_action( 'woocommerce_proceed_to_checkout', 'wc_cart_pdf_button', 21 );
This might be the incorrect part of the functions in the plugin, but I hop I got it right.
The wc_cart_pdf_process_download() function isn't really relevant. The comment states that it "Generates the PDF for download". What it's doing is responding when the user visits the PDF link by generating the requested PDF file. The important function is the one beneath that, wc_cart_pdf_button().
Now that we know the function we're interested in, what's next? In your question, you suggested editing the plugin files however it's important to avoid doing that. Editing your plugin files is a sure-fire way to guarantee the changes you make get overwritten the next time you update.
You have a couple of options:
Create a mini feature plugin.
Add the code to the bottom of your (hopefully child) theme's functions.php file.
The first option would be the recommended approach but that's going to take us well beyond the scope of the question. Placing the code in a child theme's functions.php file will be adequate for getting you up and running.
Okay, so now we know what the code we want to modify is and where we're going to store those modifications. Let's break down the actual code:
if( ! is_cart() || WC()->cart->is_empty() ) {
return;
}
This checks two things, are we on the cart page and does the cart contain items? If either is false, we're going to bail out early. You're on the checkout page, not the cart page, so even if this function were to be called, it wouldn't make it past this conditional.
<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'cart-pdf' => '1' ), wc_get_cart_url() ), 'cart-pdf' ) );?>" class="cart-pdf-button button" target="_blank">
<?php esc_html_e( 'Download Cart as PDF', 'wc-cart-pdf' ); ?>
</a>
If those two previous checks passed, generate the button output.
add_action( 'woocommerce_proceed_to_checkout', 'wc_cart_pdf_button', 21 );
This executes the code on the woocommerce_proceed_to_checkout hook which fires after the cart totals on the cart page. The same action is used by the checkout button itself.
We need to write our own function that displays that same output on the checkout page. Without knowing where you'd like the button to appear, I can't suggest which action to use. I'm using woocommerce_checkout_order_review with a priority that'll put it between the order table and the payment options. If you need to reposition it, you'll have to go through those hooks and find somewhere that feels appropriate.
You did mention in your question that this is necessary because you have your cart and checkout pages combined. You may require a completely different hook, again there's no way for me to know based on your question alone.
Here's the final code:
function stackoverflow_wc_checkout_pdf_button() {
// We're on the checkout page based on the action.
// Highly unlikely we need the is_empty() check but it can't hurt if you may find yourself reusing elsewhere.
if ( WC()->cart->is_empty() ) {
return;
} ?>
<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'cart-pdf' => '1' ), wc_get_cart_url() ), 'cart-pdf' ) );?>" class="cart-pdf-button button" target="_blank">
<?php esc_html_e( 'Download Cart as PDF', 'wc-cart-pdf' ); ?>
</a>
<?php
}
add_action( 'woocommerce_checkout_order_review', 'stackoverflow_wc_checkout_pdf_button', 15 );

How to save Meta Data in WordPress back-end with PHP

I am relatively new to Post Meta Data in the WordPress backend using PHP. I have written the code that creates the Meta Data. I need help saving the data for which I have written. It will also need to allow me to edit the data once saved.
In this case its for a text field.
I have created the Meta Data for the input field which displays well in the back-end WordPress admin area.
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'my-meta-box-id', 'Job Title', 'cd_meta_box_cb', 'people', 'normal', 'high' );
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'cd_meta_box_add', 10, 2 );
}
function cd_meta_box_cb()
{
echo "<input type='text' name='jobtitle'>";
}
I just need assistance with the code that will save the above Meta Data to the DB and allow for editing and revisions
You were almost there.
The final part of the puzzle is the function that saves the metadata, but first we need to make a few adjustments to your existing code:
add_action( 'save_post', 'cd_meta_box_add', 10, 2 ); has to be moved outside cd_meta_box_add(), and
Change add_action( 'save_post', 'cd_meta_box_add', 10, 2 ); into add_action( 'save_post', 'cd_meta_box_add' ); as this action hook only receives one parameter (the post ID), and
You need to define the function that will process the data (and it can't be cd_meta_box_add as you have it now so we'll create a new one called save_cd_meta_box_data).
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'save_cd_meta_box_data' );
function save_cd_meta_box_data( $post_id ) {
// Autosaving, bail.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// #TODO
// You should add some additional security checks here
// eg. nonce, user capabilities, etc, to prevent
// malicious users from doing bad stuff.
/* OK, it's safe for us to save the data now. */
// Make sure that it is set.
if ( ! isset( $_POST['jobtitle'] ) ) {
return;
}
// Sanitize user input.
$my_data = sanitize_text_field( $_POST['jobtitle'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_job_title', $my_data );
}
Now that we're successfully saving the metadata into the database, let's allow the user to view it / edit it:
function cd_meta_box_cb( $post )
{
$job_title = get_post_meta( $post->ID, '_job_title', true );
echo "<input type='text' name='jobtitle' value='" . esc_attr( $job_title ) . "'>";
}
The final code should look like this:
/* Register and display metabox */
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'my-meta-box-id', 'Job Title', 'cd_meta_box_cb', 'people', 'normal', 'high' );
}
function cd_meta_box_cb( $post )
{
$job_title = get_post_meta( $post->ID, '_job_title', true );
echo "<input type='text' name='jobtitle' value='" . esc_attr( $job_title ) . "'>";
}
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'save_cd_meta_box_data' );
function save_cd_meta_box_data( $post_id ) {
// Autosaving, bail.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// #TODO
// You should add some additional security checks here
// eg. nonce, user capabilities, etc, to prevent
// malicious users from doing bad stuff.
/* OK, it's safe for us to save the data now. */
// Make sure that it is set.
if ( ! isset( $_POST['jobtitle'] ) ) {
return;
}
// Sanitize user input.
$my_data = sanitize_text_field( $_POST['jobtitle'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_job_title', $my_data );
}

Wordpress -- add description below to featured image

I would like to add an annotation below featured image box in post page ,saying
'Recommended image size: 1300px (width) x 340px (height)
Is it possible in wordpress 4.2.2.
The text is for the admin user for a better guidance.
Any help is highly appreciated. Thanks in advance.
Old post here, but I was trying to do this as well. A filter since WordPress 2.9.0 offers this capacity, like so:
/**
* Filters the admin post thumbnail HTML markup to return.
*
* #since 2.9.0
* #since 3.5.0 Added the `$post_id` parameter.
* #since 4.6.0 Added the `$thumbnail_id` parameter.
*
* #param string $content Admin post thumbnail HTML markup.
* #param int $post_id Post ID.
* #param int $thumbnail_id Thumbnail ID.
*/
return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID, $thumbnail_id );
So use it like this:
function stackoverflow_30817906( $content, $post_id, $thumbnail_id ) {
if ( 'post' !== get_post_type( $post_id ) ) {
return $content;
}
$caption = '<p>' . esc_html__( 'Recommended image size: 1300px (width) x 340px (height)', 'i18n-tag' ) . '</p>';
return $content . $caption;
}
add_filter( 'admin_post_thumbnail_html', 'stackoverflow_30817906', 10, 3 );
If you want to do this without editing core files you could just use jQuery to add the text.
add_action('admin_footer', function() {
global $pagenow;
if('post.php' == $pagenow || 'post-new.php' == $pagenow) : ?>
<script>
jQuery(document).ready(function($) {
$('#postimagediv .inside').after('<div style="padding: 0 12px 12px;">Recommended image size: 1300px (width) x 340px (height)</div>');
});
</script>
<?php endif;
});
This solution isn't as 'clean' as making the change directly in the PHP file, but I think it is preferable to editing the core. With this solution you don't have to worry about remaking the change after a WordPress update.
You should go to wp-admin->includes->post.php
and around line 1295 (depending on version) you will find:
if ( !empty( $thumbnail_html ) ) {
$ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
$content = sprintf( $set_thumbnail_link, $upload_iframe_src, $thumbnail_html );
$content .= '<p class="hide-if-no-js">' . esc_html__( 'Remove featured image' ) . '</p>';
}
change it to:
if ( !empty( $thumbnail_html ) ) {
$ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
$content = sprintf( $set_thumbnail_link, $upload_iframe_src, $thumbnail_html );
$content .= '<p class="hide-if-no-js">' . esc_html__( 'Remove featured image' ) . '<span style="display:block;">Recommended image size: 1300px (width) x 340px (height)</span></p>';
}
It is not recommended to change core files as your changes can be lost during the update, but I don't recommend creating a plugin just for this small change.

adding custom page template from plugin

I'm working on building my first plugin for wordpress and am needing it to dynamically add a custom page for a login screen among other things.
The only thing I've been able to find that's anywhere near what I'm needing is here: WP - Use file in plugin directory as custom Page Template? & Possible to add Custom Template Page in a WP plugin?, but they're still not quite what I'm looking for.
Here is the code that I currently have running in my plugin...
// Add callback to admin menu
add_action( 'template_redirect', 'uploadr_redirect' );
// Callback to add menu items
function uploadr_redirect() {
global $wp;
$plugindir = dirname( __FILE__ );
// A Specific Custom Post Type
if ( $wp->query_vars["post_type"] == 'uploadr' ) {
$templatefilename = 'custom-uploadr.php';
if ( file_exists( TEMPLATEPATH . '/' . $templatefilename )) {
$return_template = TEMPLATEPATH . '/' . $templatefilename;
} else {
$return_template = $plugindir . '/themefiles/' . $templatefilename;
}
do_theme_redirect( $return_template );
}
}
function do_theme_redirect( $url ) {
global $post, $wp_query;
if ( have_posts ()) {
include( $url );
die();
} else {
$wp_query->is_404 = true;
}
}
Using this would require that my client create new page... what I'm needing is for the pluging to auto create a custom page (with a customized path, meaning .com/custompathhere) using a template file from the plugin folder, which will then contain all actions the plugin performs.
Note: This plugin is designed to run on one page, therefore reducing load-time and etc.
Thanks in advance!
Here is my code solution for adding page templates from a Wordpress plugin (inspired by Tom McFarlin).
This is designed for a plugin (the template files are searched for in the root directory of the plugin). These files are also in exactly the same format as if they were to be included directly in a theme. This can be changed if desired - check out my full tutorial http://www.wpexplorer.com/wordpress-page-templates-plugin/ for greater detail on this solution.
To customise, simply edit the following code block within the __construct method;
$this->templates = array(
'goodtobebad-template.php' => 'It\'s Good to Be Bad',
);
Full code;
class PageTemplater {
/**
* A Unique Identifier
*/
protected $plugin_slug;
/**
* A reference to an instance of this class.
*/
private static $instance;
/**
* The array of templates that this plugin tracks.
*/
protected $templates;
/**
* Returns an instance of this class.
*/
public static function get_instance() {
if( null == self::$instance ) {
self::$instance = new PageTemplater();
}
return self::$instance;
}
/**
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->templates = array();
// Add a filter to the attributes metabox to inject template into the cache.
add_filter(
'page_attributes_dropdown_pages_args',
array( $this, 'register_project_templates' )
);
// Add a filter to the save post to inject out template into the page cache
add_filter(
'wp_insert_post_data',
array( $this, 'register_project_templates' )
);
// Add a filter to the template include to determine if the page has our
// template assigned and return it's path
add_filter(
'template_include',
array( $this, 'view_project_template')
);
// Add your templates to this array.
$this->templates = array(
'goodtobebad-template.php' => 'It\'s Good to Be Bad',
);
}
/**
* Adds our template to the pages cache in order to trick WordPress
* into thinking the template file exists where it doens't really exist.
*
*/
public function register_project_templates( $atts ) {
// Create the key used for the themes cache
$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );
// Retrieve the cache list.
// If it doesn't exist, or it's empty prepare an array
$templates = wp_get_theme()->get_page_templates();
if ( empty( $templates ) ) {
$templates = array();
}
// New cache, therefore remove the old one
wp_cache_delete( $cache_key , 'themes');
// Now add our template to the list of templates by merging our templates
// with the existing templates array from the cache.
$templates = array_merge( $templates, $this->templates );
// Add the modified cache to allow WordPress to pick it up for listing
// available templates
wp_cache_add( $cache_key, $templates, 'themes', 1800 );
return $atts;
}
/**
* Checks if the template is assigned to the page
*/
public function view_project_template( $template ) {
global $post;
if (!isset($this->templates[get_post_meta(
$post->ID, '_wp_page_template', true
)] ) ) {
return $template;
}
$file = plugin_dir_path(__FILE__). get_post_meta(
$post->ID, '_wp_page_template', true
);
// Just to be safe, we check if the file exist first
if( file_exists( $file ) ) {
return $file;
}
else { echo $file; }
return $template;
}
}
add_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );
Check out my tutorial on this for more info.
http://www.wpexplorer.com/wordpress-page-templates-plugin/
I hope this helps you in what you want to do :)
I actually was able to talk to a developer friend of mine after revising the code quite a bit.
Here it is...
<?php
register_activation_hook( __FILE__, 'create_uploadr_page' );
function create_uploadr_page() {
$post_id = -1;
// Setup custom vars
$author_id = 1;
$slug = 'event-photo-uploader';
$title = 'Event Photo Uploader';
// Check if page exists, if not create it
if ( null == get_page_by_title( $title )) {
$uploader_page = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'page'
);
$post_id = wp_insert_post( $uploader_page );
if ( !$post_id ) {
wp_die( 'Error creating template page' );
} else {
update_post_meta( $post_id, '_wp_page_template', 'custom-uploadr.php' );
}
} // end check if
}
add_action( 'template_include', 'uploadr_redirect' );
function uploadr_redirect( $template ) {
$plugindir = dirname( __FILE__ );
if ( is_page_template( 'custom-uploadr.php' )) {
$template = $plugindir . '/templates/custom-uploadr.php';
}
return $template;
}
?>
I'm providing a general solution for those that want to add a template to a post from the their plugin. Use the single_template filter.
<?php
add_filter( 'single_template', 'add_custom_single_template', 99 );
function add_custom_single_template( $template ) {
return plugin_dir_path( __FILE__ ) . 'path-to-page-template-inside-plugin.php';
}
?>
Also, if you want to use the template in a specific post type, then:
<?php
add_filter( 'single_template', 'add_custom_single_template', 99 );
function add_custom_single_template( $template ) {
if ( get_post_type() == 'post-type-name'; ) {
return plugin_dir_path( __FILE__ ) . 'path-to-page-template-inside-plugin.php';
}
return $template;
}
?>

Resources