Wordpress errors from shortcodes being executed on edit page - wordpress

I am writing a wordpress plugin.
I have noticed in my debug log that i get a lot of PHP errors thrown because my shortcodes are being executed on the admin edit pages and therefore the relevant data is not available because the shortcode is loading dynamic data based upon the user front end. For example i have a function:
function myFunction_availability() {
if (is_admin()) return; // tried adding this but still get the issue
$product = $this->myFunction_get_current_product();
return "<div class='product-availability'>{$product->availability}</div>";
}
Works fine from the front end, but whenever i load the edit page from admin area i get in my log:
PHP Warning: Attempt to read property "availability" on null in /home/vagrant/yodahwp/wp-content/plugins/yodah/class.yodah.php on line 1602
As you can see from my code, i tried adding is_admin() to exit out of the function if viewing an admin page (i.e. the edit post page) but this does not seem to work.
Do any wordpress whizzes have an answer for this? I am a bit surprised that shortcodes are executed on the admin edit pages, or am I missing something?!
Thanks

This is an old question. Usually, this happens when using visual builders.
One solution is to write a condition to check if the product exists.
If using woocommerce you can try:
$product = wc_get_product( get_the_ID() );
if($product){
//continue
}
In your case, you should edit your myFunction_get_current_product() method and verify there if the product exists.

Related

Custom action on user_register hook in WordPress

I try to implement a custom function/action after a new user profile has been created in WordPress. To test the code I try to write a text in a file as proof of function execution.
Here is the code that I have inserted at the end of the active theme's functions.php file
if ( ! function_exists( 'register_for_cmsa' ) ) :
function register_for_cmsa($user_id) {
// write in an external file
// writeLogWP($msg) is a function from a file I have included in index.php
writeLogWP("A new user is: " . $user_id);
}
add_action('user_register', 'register_for_cmsa');
endif;
Therefore, I added a new user through the admin panel. As soon as I validate the standard WP add user form (wp-admin/user-new.php) I get a blank page, meaning that the above code is in trouble. But the user is added in the database (it is visible in the users' list if I comment my function). The trouble here is when executing the writeLogWP("A new user is: " . $user_id) statement inside the register_for_cmsa() function.
I tried to see if the statement works outside of the function, while always inside the functions.php file. And I noticed that it writes the message to the external file when I navigate in the WP site, BUT it publishes blank page as soon as I get into the admin dashboard section.
My code is accepted in 'site' side but it is in error in the 'admin' one.
The code is however not executed in the 'site' side because the hook is not triggered. It is triggered only if I go to the 'wp-admin/user-new.php' but ... I can' test it, as per the above reason.
I am really confused, glad to have your comments and, why not, solution.
Thanks
The index.php is not loaded when accessing the WordPress admin, hence the writeLogWP function is not being called in that case. Moving it to functions.php should solve the issue.

How to properly initialize Woocommerce Cart

I have a custom template file, rendering some products and their Add To Cart buttons, that I am trying to implement manually. When Add to Cart is pressed, the page is reloaded and a $_POST variable containing some data adds the new products. 'cart_contents_count' also reflects the added item. However, when I go to the cart page, it's empty. Please see the following code.
global $woocommerce;
if ( isset( $_POST['AddedToCart'] ) ) {
$woocommerce->cart->add_to_cart($_POST['event'], $_POST['qty']);
}
$cart_total = $woocommerce->cart->cart_contents_count;
When I however go to the normal default shop page ( /shop/ ) and add a product from there, my cart page indicates that this product has been added. When I NOW go to my custom page and add products from that Add To Cart button, it works perfectly.
It seems to me that, before I run the above-mentioned code, I must check if a Cart Session has been initialized, and if not, initialize it. Could someone please confirm for me that I understand it right and show me how to initialize the cart?
Here is a solution if your custom form is on a page template. This code goes in your functions.php file. Be sure to change yourtheme_template to something more unique. Also, change the items in the $session_templates array to the template filenames where you want this filter to be used. It uses the template_include filter, which isn't an easy filter to track down, let alone $woocommerce->session->set_customer_session_cookie(true) - Special thanks to #vrazer (on twitter) for the help.
function yourtheme_template($template) {
//List of template file names that require WooCommerce session creation
$session_templates = array(
'page-template-file-name.php', 'another-page-template-filename.php'
);
//Split up the template path into parts so the template file name can be retrieved
$parts = explode('/', $template);
//Check the template file name against the session_templates list and instantiate the session if the
//template is in the list and the user is not already logged in. If the session already exists from
//having created a cart, WooCommerce will not destroy the active session
if (in_array($parts[count($parts) - 1], $session_templates) && !is_user_logged_in()) {
global $woocommerce;
$woocommerce->session->set_customer_session_cookie(true);
}
return $template;
}
//Filter to run the WooCommerce conditional session instantiation code
add_filter('template_include', 'yourtheme_template');
I resolved this problem by making sure the $woocommerce->cart->add_to_cart() line is positioned before any headers are sent. I.E, before get_header() is called on my custom template.
In the WooCommerce version 2.5 they change the way the sessions works. https://woocommerce.wordpress.com/2015/10/07/new-session-handler-in-2-5/
What i did was install this plugin https://github.com/kloon/woocommerce-large-sessions then my cart is not empty any more with guess users.
I hope it helps someone else.

wordpress plugin hooks method

I am creating a plugin for wordpress.I need database interaction.So i need to run some queries to create table.I want to run those queries in a php function.I need to run this function when this plugin will active.What hooks should i use for this purpose?? Now i am using this:
add_action( 'admin_menu', 'bs_check_database_creation' );
This is working fine so far.But i need appropriate hooks to run this function once when this plugin will activate.
Another queries : i want add a link of this plugin in header/footer/sidebar for end user to go to the plugin end user page.How should i do this?
Currently i've manually added a link for this in wordpress template page.
Thanks in advance
It depends when you want the hook to run, But I think that init or admin_init will be right for you becasue they are the earliest ones running respectively on front and back end.
EDIT : (After comment) The INIT and admin_init are ment to use whenever a plugin needs to RUN, and not on first activation (or install) . writing "I need to run this function when this plugin will active " is a bit confusing :-) active means when it start to run , or when it is actually ACTIVATED ?
If you need to run a function upon ACTIVATION , then it is a bit different..
register_activation_hook(__FILE__, 'o99_brsa_on_activate');
function o99_brsa_on_activate() {
// do your stuff on activation
}
About the links, I am not sure what you mean by end user page ... Do you mean action links ?
And what footer do you mean ? the Admin or the Front ? ( After answering those issues I can try and reply - Even if it is a material for another question .)
As for links in the header / footer . If ou are planning to host this plugin in the wordpress repository please know that it is somewhat against the terms ( unless you request specific permission from the user )
Anyhow , this will do :
function o99_add_to_footer() {
echo '<p>This is inserted at the bottom</p>';
}
add_action('wp_footer', ' o99_add_to_footer');

Wordpress plugins function code

I am trying to make a simple plugin that displays some info in the users profile page ( I have managed this part) but what I am not getting to work is I want to add a function that will check to see if a file exists on in a folder ( I can do this part ) but when I add a function into the plugin code it does not work or stops the page from showing up.
Any help would be great I just need to trigger the function on load of user looking at there profile.
function check_file(){
if($file == 'me.jpg'){
//do something
}
else{}
}
check_file();
Found the answer
add_action( 'show_user_profile', 'check_file' );
Above line will run the check_file function when user will see the profile.

wordpress add_action('save_post', 'my_function) not working

I am trying to trigger an even upon saving / updating a post in wordpress... see here:
add_action('save_post', 'generate_location');
function generate_location($post_id) {
echo "hey";
}
the problem is that its not working...
any ideas why? Syntax?
WordPress implements the Post/Redirect/Get pattern to avoid duplicate form submissions, so you're not going to see anything echo'd from a save_post callback.
Instead, you can do a wp_die( 'hey' ) instead, or log something to the database or file system.
I don't know whether you got this working, but I was having the same issue and discovered how to fix it!
in wp-includes/post.php on line 2940 (at the time of writing), this if/else is run whilst saving a post:
if ( !empty($page_template) && 'page' == $data['post_type'] ) {
You will notice that, if there is an error with the template the function stops there and save_post is never called.
In my case, the posts I was trying to save were imported from a pre-existing site. The new site had no page templates at all, so WP was still trying to save the page with the template from before, failing, and thus; save_post was never called.
I added
/* Template Name: Default Template */
to page.php, bulk edit, selected the template and saved. Remove the template name from page.php (as it shows up twice(, and now save_post is triggered every time.
This was the solution in my case anyway. i'm sure it'll affect someone else, somewhere down the line.

Resources