I'm trying to make a plugin to add a column to print some pdf files using the library fpdf using the code:
function rz_listing_pdf_column($columns) {
$columns['pdf'] = __( 'PDF', 'text_domain' );
return $columns;
}
add_filter( 'manage_rz_listing_posts_columns', 'rz_listing_pdf_column' );
function rz_listing_pdf_column_content($column, $post_id) {
if ( $column == 'pdf' ) {
$pdf_link = plugins_url('pdf.php?id=' . $post_id, __FILE__);
echo 'Download';
}
}
add_action( 'manage_rz_listing_posts_custom_column', 'rz_listing_pdf_column_content', 10, 2 );
this should open "pdf.php?id=" or print a PDF file using the post meta values of the clicked post, my issue it's that if I try to use
require_once plugin_dir_path(__FILE__) . 'fpdf/fpdf.php';
doesn't work, so neither I can't use:
$player1_birthday = get_post_meta($post_id, 'rz_player1_birthday', true);
because it's not reading anything coming from Wordpress, I'm new on this so I know I'm doing something wrong, any help?
I have been trying to add a Nonce to inline JS in Wordpress primarily focusing on WooCommerce. So far, I've managed to add the Nonce to registered JS but the inline JS code generated out of plugins such as Woocommerce isn't getting the Nonce added.
The approach which has worked for registered JS is...
add_filter( 'script_loader_tag', 'add_nonce_to_script2', 10, 3 );
function add_nonce_to_script2( $tag, $handle, $src ) {
global $my_nonce2;
$my_nonce2 = wp_create_nonce('my__script__nonce');
return '<script type="text/javascript" src="' . esc_url( $src ) . '" nonce="nonce-' . esc_attr( $my_nonce2 ) . '"></script>';
}
The approach which isn't working, maybe because I don't know the right $var for data to pass to the below solution from Woocommerce, any guidance would be appreciated.
Example code I'm trying to target.
<script type='text/javascript'>
/* <![CDATA[ */
var wc_add_to_cart_params = {"ajax_url":"\/wp-admin\/admin-ajax.php","wc_ajax_url":"\/?wc-ajax=%%endpoint%%","i18n_view_cart":"View cart","cart_url":"https:\/\/mysite.com\/cart\/","is_cart":"","cart_redirect_after_add":"no"};
/* ]]> */
</script>
Solution that isn't working below...
add_filter( 'script_loader_tag', 'add_nonce_to_script_tag', 10, 3 );
function add_nonce_to_script_tag( $tag, $handle, $src ) {
// Check the $handle and respond accordingly
if ( $handle === 'my-script' ) {
$nonce_value = wp_create_nonce('my__script__nonce'); // or ref to an existing nonce
$replace = sprintf("javascript' nonce='%s'>", $nonce_value );
$tag = str_replace( "javascript'>", $replace, $tag);
}
return $tag;
}
// Then... $data is the inline JS from wherever
wp_add_inline_script('my-script', $data, 'before');
So, i've built myself an enqueue'd stylesheet concatenator, while it works, what I've found is that the "dependencies" seem to be out of order... in this instance, I deregister and dequeue my "custom" stylesheet, register and enqueue my concatenated stylesheet, and then "re" register and "re" enqueue my custom style sheet using the concatenated handle as the dependency for it... and it always loads before the concatenated stylesheet.
Any ideas why this may be happenning? In my child-theme, I am enqueing "custom" at the default priority, in the parent theme, is where I am performing the concatenation, and my action has the highest possibly priority.
The Code:
protected function concatenate_css( $_cache_time ) {
add_action( 'wp_enqueue_scripts', function( ) use ( $_cache_time ) {
// need our global
global $wp_styles;
// our css string holder
$_css_string = '';
// path to the theme
$_theme_path = get_stylesheet_directory( );
// uri to the theme
$_theme_uri = get_stylesheet_directory_uri( );
// new file path
$_new_css = $_theme_path . '/style.concat.css';
// force the order based on the dependencies
$wp_styles -> all_deps( $wp_styles -> queue );
// setup our exclusions
$_exclude = array( 'custom', 'concatcss', );
// loop through everything in our global
foreach( $wp_styles -> queue as $_hndl ) {
// get the source from the hanlde
$_path = $wp_styles -> registered[$_hndl]->src;
// if we have a "custom" handle, we do not want to process it, so ... skip it
// we also do want to process any source that is not set
if( ! in_array( $_hndl, $_exclude ) && $_path ) {
// we also only want to do this for local stylehseets
if ( strpos( $_path, site_url( ) ) !== false ) {
$_path = ABSPATH . str_replace( site_url( ), '', $_path );
// now that we have everything we need, let's hold the contents of the file in a string variable, while concatenating
$_css_string .= file_get_contents( $_path ) . PHP_EOL;
// now remove the css from queue
wp_dequeue_style( $_hndl );
// and deregister it
wp_deregister_style( $_hndl );
}
}
}
// dequeue and deregsiter any "custom" style
wp_dequeue_style( 'custom' );
wp_deregister_style( 'custom' );
// now write out the new stylesheet to the theme, and enqueue it
// check the timestamp on it, versus the number of seconds we are specifying to see if we need to write a new file
if( file_exists( $_new_css ) ) {
$_ftime = filemtime( $_new_css ) + ( $_cache_time );
$_ctime = time( );
if( ( $_ftime <= $_ctime ) ) {
file_put_contents( $_new_css, $_css_string );
}
} else {
file_put_contents( $_new_css, $_css_string );
}
wp_register_style( 'concatcss', $_theme_uri . '/style.concat.css', array( ), null );
wp_enqueue_style( 'concatcss' );
// requeue and reregister our custom stylesheet, using this concatenated stylesheet as it's dependency
wp_register_style( 'custom', $_theme_uri . '/css/custom.css?_=' . time( ), array( 'concatcss' ), null );
wp_enqueue_style( 'custom' );
}, PHP_INT_MAX );
}
Screenshot of the page source
Just register your concatenated script, but don't enqueue it.
wp_register_style( 'concatcss', $_theme_uri . '/style.concat.css', array( ), null );
// requeue and reregister our custom stylesheet, using this concatenated stylesheet as it's dependency
wp_enqueue_style( 'custom', $_theme_uri . '/css/custom.css?_=' . time( ), array( 'concatcss' ), null );
I have added a bunch of new fields to my checkout form in woocommerce. it reads in the finished php file as such;
<form name="checkout" method="post" class="checkout woocommerce-checkout processing" action="http://localhost:100/wordpress/checkout/" enctype="multipart/form-data" style="position: relative; zoom: 1;">
<div id="pagePreview">
<input type="file" name="CheckoutImageUpload">
<div class="BBtextInputFrontend">
<input class="BBTextBoxFront" placeholder="placeholder">
<input class="BBInitialValue BBData" type="text" name="BBInitialValue[]">
</div>
<div class="BBtextInputFrontend">
<input class="BBTextBoxFront" placeholder="placeholder">
<input class="BBInitialValue BBData" type="text" name="BBInitialValue[]">
</div>
</div>
<!-- the rest is the default woocommerce billing inputs -->
<div class="col2-set" id="customer_details">
<div class="col-1">
<div class="woocommerce-billing-fields">
<h3>Billing Details</h3>
the problem is that the input
<input type="file" name="CheckoutImageUpload">
never returns a value in the $_FILES array. in fact, the $_FILES array always returns an empty array. I can get the other values through $_POST with no issue. but not files. putting the plugin on a fresh install on another separate computer yields the exact same results.
I'm currently using this code to find the values:
function add_image($order_id) {
//if they DID upload a file...
if ($_FILES['CheckoutImageUpload']['name']) {
?>Y<?php
die();
}
else {
?>N<?php
die();
}
}
add_action( 'woocommerce_checkout_update_order_meta', 'add_image', 100, 1);
can anyone help? I feel like I'm losing my mind
The complete code mentioned I've added below. what you see above is a shortening of it while keeping the important parts.
<?php
/*
#package BBPlugin
#wordpress_plugin
Plugin Name: Brave books book preview plugin
Plugin URI: null
Description: Allows the user to single out words to be replaced for a preview in a book.
Author: Goodship
Version: 0.0.2
Author URI: www.Goodship.co.za
*/
// If this file is called directly, abort execution.
if ( ! defined( 'WPINC' ) ) {
die;
}
ini_set('error_reporting', E_ALL);
// This will attach the file needed for the class which defines
// meta boxes, their tabs, views and partial content.
require_once plugin_dir_path( __FILE__ ) . 'admin/class-BBPlugin.php';
/**
The class that represents the meta box that will display
the navigation tabs and each of the fields for the meta box.
*/
require_once plugin_dir_path( __FILE__ ) . 'admin/class-BBPlugin-meta-box.php';
/*
Execute the plugin.
Everything for this particular plugin will be done so from within
the Author_Commentary/admin subpackage. This means that there is no reason to setup
any hooks until we're in the context of the Author_Commentary_Admin class.
#since 0.0.1
*/
/*
This will create an instance of the BBPlugin_Admin class
from the class file mentioned previously as soon as the plugin is activated,
After accepting the plugin name and version parameters.
*/
add_shortcode("BB", "BraveBooksShortCode");
function BraveBooksShortCode( $atts, $content = null , $checkout) {
$inputDiv = '<div class="BBtextInputFrontend">
<input class="BBTextBoxFront" type="text" placeholder="'.$content.'" />
<input class="BBInitialValue BBData" type="text" name="BBInitialValue[]" />
</div>';
return $inputDiv;
}
function Run_BBPlugin() {
$BBPlugin = new BBPlugin_Admin('BB-Plugin', '0.0.1');
$BBPlugin->initialize_hooks();
}
Run_BBPlugin();
wp_register_style( 'postStyles', '/'.'wp-content/plugins/BBPluginv2/admin/assets/css/BBClasses.css' );
wp_enqueue_style('postStyles');
wp_enqueue_script( 'jquery' );
function load_my_script(){
wp_register_script(
'functions',
'/wp-content/plugins/BBPluginv2/admin/assets/js/functions.js' ,
array( 'jquery' )
);
wp_enqueue_script( 'functions' );
}
add_action('wp_enqueue_scripts', 'load_my_script');
function woo_redirect_to_checkout() {
$checkout_url = WC()->cart->get_checkout_url();
return $checkout_url;
}
add_filter ('woocommerce_add_to_cart_redirect', 'woo_redirect_to_checkout');
function check_if_cart_has_product( $valid, $product_id, $quantity ) {
global $woocommerce;
$woocommerce->cart->empty_cart();
$woocommerce->cart->add_to_cart($product_id,0);
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );
function change_add_to_cart_loop( $product ) {
global $product; // this may not be necessary as it should have pulled the object in already
return 'READ MORE';
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'change_add_to_cart_loop' );
function woo_custom_cart_button_text() {
return __( 'Buy this book', 'woocommerce' );
}
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' ); // 2.1 +
function wc_remove_all_quantity_fields( $return, $product ) {
return true;
}
add_filter( 'woocommerce_is_sold_individually', 'wc_remove_all_quantity_fields', 10, 2 );
function wc_add_to_cart_message_filter($message, $product_id = null) {
$message = sprintf( 'Please remember to enter your details before purchase.');
return $message;
}
add_filter ( 'wc_add_to_cart_message', 'wc_add_to_cart_message_filter', 10, 2 );
// display the extra data in the order admin panel
function kia_display_order_data_in_admin( $order , $order_id){
global $woocommerce, $post;?>
<div class="order_data_column">
<h4><?php _e( 'Words used' ); ?></h4>
<?php
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item['product_id'];
echo '<p>' .json_encode(get_post_meta($product_id, 'BBPlugin-Pages', true) ). '</p>';
echo '<p>' .json_encode(get_post_meta($post->ID, 'your_key', true) ). '</p>';
}
$pageJSONData = json_encode(get_post_meta($product_id, 'BBPlugin-Pages', true));
$wordsJSONData = json_encode(get_post_meta($post->ID, 'your_key', true));
?>
<script type='text/javascript'>
var pageArray = <?php echo $pageJSONData ?>;
var wordsArray = <?php echo $wordsJSONData ?>;
</script>
Create PDF
</div>
<?php
}
add_action( 'woocommerce_admin_order_data_after_order_details', 'kia_display_order_data_in_admin' );
/*
** Getting an image to upload
*/
function add_image($order_id, $posted) {
$sanitized_input_data = array();
$inputsData = $_POST['BBInitialValue'];
$filesData = $_FILES['CheckoutImageUpload'];
$testLog = fopen("testicle.txt","w") or exit ("Unable to open file!");
fwrite ($testLog , "added files: " . $_FILES['CheckoutImageUpload']['name']);
foreach ( $inputsData as $inputsBoxNumber => $inputBoxData ) {
$inputArray = explode( "|", $inputBoxData );
if ( ! empty( $inputBoxData ) ) {
$BBData = array(
'shortcode' => $inputArray[0],
'word_used' => $inputArray[1]
);
fwrite ($testLog , "found files: " . $inputArray[0]);
$sanitized_input_data[ $inputsBoxNumber ] = $BBData;
}
}
fclose ($testLog);
update_post_meta( $order_id, 'your_key', $sanitized_input_data);
//if they DID upload a file...
if ($_FILES['CheckoutImageUpload']['name']) {
//if no errors...
if (!$_FILES['CheckoutImageUpload']['error'] ) {
$valid_file = true;
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['CheckoutImageUpload']['tmp_name'] ); //rename file
if ($_FILES['CheckoutImageUpload']['size'] > ( 1024000 ) ){ //can't be larger than 1 MB
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
echo $message;
die();
}
//if the file has passed the test
if ( $valid_file ) {
//move it to where we want it to be
//copy( $_FILES['CheckoutImageUpload']['tmp_name'], plugin_dir_path( __FILE__ ) . 'admin' );
$message = 'Congratulations! Your file was accepted.';
echo $message;
$BBdirectory = wp_upload_dir();
$BBdirectory = $BBdirectory['path'] .'/'. $order_id .'/';
if (!file_exists($BBdirectory)) {
mkdir($BBdirectory, 0777, true);
if (move_uploaded_file($_FILES['CheckoutImageUpload']['tmp_name'], $BBdirectory . $_FILES["CheckoutImageUpload"]['name'])) {
echo "Uploaded";
die();
} else {
echo "File was not uploaded";
die();
}
}
}
} //if there is an error...
else {
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: ' . $_FILES['CheckoutImageUpload']['error'];
echo $message;
}
}
else {
}
}
add_action( 'woocommerce_checkout_update_order_meta', 'add_image', 99, 2);
//add_action( 'woocommerce_checkout_update_order_meta', 'add_image');
/*
function platoon_add_order_meta( $order_id, $posted ) {
$sanitized_input_data = array();
$inputsData = $_POST['BBInitialValue'];
foreach ( $inputsData as $inputsBoxNumber => $inputBoxData ) {
$inputArray = explode( "|", $inputBoxData );
if ( ! empty( $inputBoxData ) ) {
$BBData = array(
'shortcode' => $inputArray[0],
'word_used' => $inputArray[1]
);
$sanitized_input_data[ $inputsBoxNumber ] = $BBData;
}
}
update_post_meta( $order_id, 'your_key', $sanitized_input_data);
}
add_action( 'woocommerce_checkout_update_order_meta', 'platoon_add_order_meta', 99, 2 );
*/
function add_checkout_notice() {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
$item = end($items)['data']->post->ID;
$pages = get_post_meta( $item, 'BBPlugin-Pages', true );
echo '<div id="pagePreview">';
echo '<input type="file" name="CheckoutImageUpload" />';
foreach ( $pages as $pageNumber=>$pageData ) {
if ($pageData["page_type"] == "text_only"){
$designedData = $pageData["text"];
$designedData = do_shortcode ( $designedData, false );
echo $designedData;
}
else if ($pageData["page_type"] == "2up"){
$designedData = $pageData["text"];
$designedData = do_shortcode ( $designedData, false );
echo $designedData;
}
}
echo '</div>';
?>
<script>
function Test(){
<?php
/*
$testLog = fopen("testicle.txt","w") or exit ("Unable to open file!");
fwrite ($testLog , "added files: " . $_FILES['CheckoutImageUpload'] . $_POST['BBInitialValue']);
fclose ($testLog);
*/
?>
}
</script>
<a onclick="Test()" class="btn">Call PHP Function</a>
<?php
}
add_action( 'woocommerce_checkout_before_customer_details', 'add_checkout_notice');
/*
** end of image upload
*/
?>
I've also included the code below for debugging, and it also returns nothing, so it isn't exclusive to the action.
?>
<script>
function Test(){
<?php
$testLog = fopen("testicle.txt","w") or exit ("Unable to open file!");
fwrite ($testLog , "added files: " . $_FILES);
fclose ($testLog);
?>
}
</script>
<a onclick="Test()" class="btn">Call PHP Function</a>
<?php
"#Fred -ii- I used that link you added to get all the errors and I received this error: [Thu Mar 31 12:23:09.121930 2016] [:error] [pid 11208:tid 1248] [client 127.0.0.1:51335] PHP Notice: Undefined index: CheckoutImageUpload in Z:\Work\J00028 - Brave books plugin\Wordpress stack\apps\wordpress\htdocs\wp-content\plugins\BBPluginv2\BBPlugin.php on line 290, referer: http://localhost:100/wordpress/product/a-book/ Does this help? – Captain Dando"
Your file's name attribute is name="checkoutupload" but you're using $_FILES['CheckoutImageUpload'] throughout your code.
So, to keep you from changing all of the $_FILES['CheckoutImageUpload'] to the named attribute, simply change the file name attribute to name="CheckoutImageUpload".
Also make sure that the folder you are uploading to has the correct path and that it has the proper permissions to write to it.
do check var_dump($_FILES); for debugging
check $_FILES['yourFieldName']['error'] for file upload errors. php stores any errors encountered during upload, allocation, etc in ['errors']
$_FILES is an array so fwrite ($testLog , "added files: " . $_FILES); wont work var_dump should work best most of the time. (for silent debugging use a recursive foreach loop)
should you encounter errors in $_FILES['yourFieldName']['error'], most of the time the filesize is to big (php.ini) or the folder is not writeable
try the following:
function add_image($order_id) {
//var_dump($_FILES);
$errors = array();
if (
!isset($_FILES['CheckoutImageUpload']['error']) ||
is_array($_FILES['CheckoutImageUpload']['error'])
) {
$errors[] = 'Invalid file.';
}
switch ($_FILES['CheckoutImageUpload']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
$errors[] = 'you sent no file';
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$errors[] = 'file too big'
default:
$errors[] = 'unknown error';
}
// check filesize manually
if ($_FILES['CheckoutImageUpload']['size'] > 50000) { // whatever your php.ini says
$errors[] = 'file too big';
}
return json_encode($errors);
}
Also try small text files for dev purposes. If big files fail increase these php.ini values:
max_input_time
max_execution_time
upload_max_filesize
post_max_size
session.gc_maxlifetime
I'd simplify and just test a simple file upload first
Here is a sample. Save it as test_upload.php and access it directly through your web server to test file uploads.
<?php
// test_upload.php
// Tests php file upload capabilities
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<pre>";
print_r($_FILES);
exit();
}
?>
<form enctype="multipart/form-data" method='post' action=''>
<input type='file' name='file' />
<input type='submit' value='submit form' />
</form>
If this doesn't work, you need to check your php.ini and also make sure that the configured temporary directory is writable by the web server.
You can find your system's temporary directory by running the following:
php -B 'echo sys_get_temp_dir(); echo "\n"; exit();'
As this is a ajax method, you need to add a ajax method to upload the files as the settings are slightly different. I think the performance of this will be poor but see what you think!
You need to check a few things in the script
1. I think i have used the correct identifer for the form (classname="checkout") examine your outputted html to ensure this is correct
2. This will only work with 1 file upload on the page, modify jQuery(document) if you need to narrow this down
3. Ajaxurl -- read the notes in the code, i'd recommend you check this first before trying the script
jQuery(form.checkout).on('submit', function(){
var fd = new FormData();
//searches the whole document, i am assuming you only need 1 file uploaded
var file = jQuery(document).find('input[type="file"]');
var individual_file = file[0].files[0];
fd.append("imagefile", individual_file);
fd.append('action', 'upload_image');
jQuery.ajax({
type: 'POST',
url: ajaxurl, // nb-----------------have you got a variable for ajaxurl? if not insert var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; somewhere in your template...or google the wp way!
data: fd,
contentType: false,
processData: false,
success: function(response){
//just spit out the response to the console to catch php errors etc..
console.log(response);
}
});
});
In your functions.php...
function upload_image(){
echo 'action had been called';
var_dump($_FILES);
// work with files!
}
add_action('wp_ajax_upload_image', 'upload_image');
add_action('wp_ajax_nopriv_upload_image', 'upload_image');
Did you dump the $_FILES completly?
Maybe you have an other field with the same form name.
If you would have posted the complet form it would be easier (as already mentioned).
Another reason might be, that your php stack doesn't have write permission to the upload folder and then returns nothing.
Check your server logs.
It might tell you what happened.
Something else I just thought off.
Use Crome and check what requests have been fired.
But make shure that you hightlited the checkbox in the network section to persist the session.
Your Browser might reload the page without you recognizing it.
:)
i use this code to deregister jquery from wp_head():
<?php if ( !is_admin() ) wp_deregister_script('jquery'); wp_head(); ?>
i want jquery just added when user on bbpress page, but it's not working:
<?php
if (is_bbPress()) (wp_register_script('jquery'); wp_head();}
else (!is_admin()) (wp_deregister_script('jquery'); wp_head();}
?>
can somebody help me fix this please
The proper way to enqueue scripts and styles is to use wp_enqueue_script:
http://codex.wordpress.org/Function_Reference/wp_enqueue_script
So, for example:
function my_enqueue_script() {
if ( is_bbPress() ) {
// The name used as a handle for the script
$handle = 'script-name';
// The url to the script
$src = get_template_directory_uri() . '/js/example.js';
// Array of the handles of all the registered scripts that must be loaded before this script
$deps = array();
// The version number of the script (if it has one)
$ver = '1.0.0';
// Should the script be placed in the document footer or the head?
$in_footer = true;
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
}
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_script' );