How can I retrieve a variable from a function? - php

I know there are a few items out on the internet over how to achieve this, but I can't get it to work...
Can anyone please point me in the right direction?
I currently have two functions. I want to use the variable ($new_data) from function1 inside function2.
Function 1:
function manipulate_form_submission( $record, $ajax_handler ) {
$form_name = $record->get_form_settings( 'form_name' );
$form_data = $record->get( 'fields' );
//change the names of fields before we send them somewhere
$new_data = array(
'email' => isset( $form_data['email']['value'] ) ? $form_data['email']['value'] : '',
'url' => isset( $form_data['url']['value'] ) ? $form_data['url']['value'] : ''
)
}
Function 2:
add_action( 'woocommerce_payment_complete', 'so_payment_complete' );
function so_payment_complete( $order_id ){
$order = wc_get_order( $order_id );
$response = wp_remote_post( 'https://mywebsite.com/insert_values.php', array( 'body' => $new_data) );
}
Thanks in advance!

Just initialize the variable outside the two functions like this:
<?php
$new_data = false;
function manipulate_form_submission( $record, $ajax_handler ) {
global $new_data;
$new_data = "New value";
}
function so_payment_complete( $order_id ){
// The variable is accessible here
global $new_data;
echo $new_data;
}
?>

Related

How to inspect variables inside "register_activation_hook" in WordPress

I'm new to WordPress/PHP and I'm trying to create a WP plugin. I want to be able to inspect some code inside the register_activation_hook. This is the code that's being executed inside the register_activation_hook:
$data_store = \WC_Data_Store::load('webhook');
$all_hooks = $data_store->search_webhooks(
array(
'limit' => 10,
)
);
$_items = array_map('wc_get_webhook', $all_hooks->webhooks);
foreach ($_items as $webhook) {
$name = $webhook->get_name();
echo $name; // trying to inspect the name here
if ($name === "Test Hook") {
$webhook->set_status('active');
$webhook->save();
}
}
When I install and then activate the plugin, I don't get any output anywhere, even if I use alert instead of echo.
I saw some people saying that you shouldn't output anything inside the register_activation_hook. If that's the case, how can we inspect the values inside this hook?
I tried using a debugging plugin called Query Monitor, but it's also not capturing anything.
You can't pass output to the register_activation_hooksince it will return a Headers already sent error, you should catch the values you need with a transient and pass it to the admin_notices action, similar to this:
register_activation_hook( __FILE__, 'initiate_webhooks' );
function initiate_webhooks(){
$data_store = \WC_Data_Store::load( 'webhook' );
$all_hooks = $data_store->search_webhooks(
array(
'limit' => 10,
)
);
$_items = array_map( 'wc_get_webhook', $all_hooks->webhooks );
set_transient( 'active_webhooks', wp_json_encode( $_items ) , 60 );
foreach ( $_items as $webhook ) {
$name = $webhook->get_name();
if ( $name === "Test Hook" ) {
$webhook->set_status( 'active' );
$webhook->save();
}
}
}
add_action( 'admin_notices', function() {
$webhooks = get_transient( 'active_webhooks' );
if ( false !== $webhooks ) {
?>
<div class="notice notice-success is-dismissible">
<?php
$webhooks = json_decode( $webhooks );
foreach( $webhooks as $webhook ) {
echo $webhook;
}
?>
</div>
<?php
}
});
Don't forget to delete the transient.
https://developer.wordpress.org/apis/transients/

String with special character not adding in database WordPress

I am getting an array from order metadata and just taking two values from that array and adding them again in the database with new meta_key
function custom_order_meta_tracking($order_id) {
global $woocommerce, $post, $wpdb;
$orderid = new WC_Order($post->ID);
$order_id = trim(str_replace('#', '', $orderid->get_order_number()));
if ( metadata_exists( 'post', $order_id, '_wc_shipment_tracking_items' )) {
$gettracking_array = get_post_meta($order_id,'_wc_shipment_tracking_items', true);
foreach ($gettracking_array as $key => $item ) {
$tracking_number = $gettracking_array[$key]['tracking_number'];
$tracking_provider = $gettracking_array[$key]['tracking_provider'];
$tracking_providers = $wpdb->_real_escape( $tracking_provider );
update_post_meta($order_id, '_tracking_number', $tracking_number, $prev_value);
update_post_meta($order_id, '_tracking_provider', $tracking_providers, $prev_value);
}
}
}
add_action( 'woocommerce_order_status_completed', 'custom_order_meta_tracking', 10, 3 );
now the issue I am facing is that $tracking_providers have value with special characters like "after.ship" and in this case it did not add any value in database.
I tried "wpdb::_real_escape" but not working.
please help
thanks

How do I get the value of a variable inside another

I'm trying to get the $pi1 and $pi2 variable values inside of the add_custom_price function, but nothing seems to be working.
I have looked at setting variables to be accessible from function classes but I'm not sure I understand how to access them correctly.
add_filter( 'gform_confirmation', array(gravity_pi,custom_confirmation), 10, 4 );
class gravity_pi {
public $pi1;
public $pi2;
public function custom_confirmation( $confirmation, $form, $entry, $ajax, $product_id, $pi1, $pi2 ) {
if( $form['id'] == '2' ) {
$post = get_post( $entry['post_id'] );
$this->pi1 = rgar( $entry, '20' );
$this->pi2 = rgar( $entry, '21' );
$exclude_list = array("pi24","pi64","pi65","pi66","pi67","pi68","pi69","pi70","pi71","pi72","pi73","pi74","pi75","pi76","pi77","pi78","pi79","pi80","pi81","pi82");
if(!in_array($this->pi1, $exclude_list) && !empty($this->pi1)){
$target_product_id = '86';
$pid1 = '86';
}else{
$pid1 = preg_replace("/[^0-9,.]/", "", $this->pi1 );
}
if(!in_array($pi2, $exclude_list) && !empty($this->pi2)){
$target_product_id = '87';
$pid2 = '87';
}else{
$pid2 = preg_replace("/[^0-9,.]/", "", $this->pi2);
}
$product_ids = ''.$pid1.','.$pid2.'';
$url = 'https://*****.com/cart/?add-to-cart='.$product_ids.'';
$confirmation = array( 'redirect' => $url );
}
return $confirmation;
}
public function add_custom_price( $cart_object, $entry,$form, $field, $input_id ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
if( 86 == $value['data']->id ) {
$value['data']->set_price( $this->pi1 );
}
if( 87 == $value['data']->id ) {
$value['data']->set_price( $this->pi2 );
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', array(gravity_pi,add_custom_price));
You need to use $this to get/set any property in the class.
// set pi1 property value
$this->pi1 = 10;
//print/get property value
echo $this->pi1;
When you're setting the class properties (pi1 & pi2) you need to reference them in the same way you access them. Ex.
<?php
...
$this->pi1 = rgar($entry, '20');
Change all references (except where you declare them) of $pid1 to $this->pid1. Do this for $pid2 too.
Check this video out - https://www.youtube.com/watch?v=4c4nP7GLL1c

Woocommerce CSV export not showing values

I've noticed a strange behaviour of one of my functions. Just take a look. Using first function I'm displaying some custom fields data in the backend:
add_filter( 'manage_edit-shop_order_columns', 'MY_COLUMNS_FUNCTION', 10 );
function MY_COLUMNS_FUNCTION( $columns ) {
$new_columns = ( is_array( $columns ) ) ? $columns : array();
unset( $new_columns['order_actions'] );
//edit this for you column(s)
//all of your columns will be added before the actions column
$new_columns['product_name'] = 'Product';
$new_columns['authors_income'] = 'Author';
$new_columns['order_actions'] = $columns['order_actions'];
return $new_columns;
}
add_action( 'manage_shop_order_posts_custom_column', 'MY_COLUMNS_VALUES_FUNCTION', 2 );
function MY_COLUMNS_VALUES_FUNCTION( $column ) {
global $post;
$order = new WC_Order( $post->ID );
$items = $order->get_items();
//start editing, I was saving my fields for the orders as custom post meta
//if you did the same, follow this code
if ( $column == 'authors_income' ) {
foreach ( $items as $item ) {
echo $item['PLN-dla-autora'];
echo ' zł';
}
}
if ( $column == 'product_name' ) {
foreach ( $items as $item ) {
echo $item['name'];
}
}
}
add_filter( "manage_edit-shop_order_sortable_columns", 'MY_COLUMNS_SORT_FUNCTION' );
function MY_COLUMNS_SORT_FUNCTION( $columns ) {
$custom = array(
//start editing
'authors_income' => 'PLN-dla-autora',
'product_name' => 'name'
//stop editing
);
return wp_parse_args( $custom, $columns );
Everything works there like a charm. Then I have second function, which somehow does the same, yet it will print the data into the CSV file. Unfortunatelly, this code doesnt work (it display only column header, no data included). I dont see any major differences between those functions so why is that?
function wc_csv_export_modify_column_headers( $column_headers ) {
$new_headers = array(
'author_income' => 'PLN dla autora',
// add other column headers here in the format column_key => Column Name
);
return array_merge( $column_headers, $new_headers );
}
add_filter( 'wc_customer_order_csv_export_order_headers', 'wc_csv_export_modify_column_headers' );
// set the data for each for custom columns
function wc_csv_export_modify_row_data( $order_data, $order ) {
$custom_data = array(
'author_income' => get_post_meta( $order->id, 'PLN dla autora', true ),
// add other row data here in the format column_key => data
);
return array_merge( $order_data, $custom_data );
}
add_filter( 'wc_customer_order_csv_export_order_row', 'wc_csv_export_modify_row_data', 10, 2 );

Add foreach to function

I am trying to edit a wordpress php file with the following function :
add_action('userpro_after_profile_head','userpro_sc_bar', 99);
function userpro_sc_bar( $args ) {
global $userpro, $userpro_social;
extract($args);
( display content buttons here )
}
I am trying to add a button to this function from a different plugin and I need to add the following global rules :
foreach ( $sellers['users'] as $seller ) {
$store_info = get_store_info( $seller->ID );
$store_url = get_store_url( $seller->ID );
}
When I add the two lines $store_info and $store_url to the global rules, it works, but I'm not getting the $seller ID that is defined with the foreach argument
When I add the whole thing into the global rules like this :
add_action('userpro_after_profile_head','userpro_sc_bar', 99);
function userpro_sc_bar( $args ) {
global $userpro, $userpro_social;
extract($args);
foreach ( $sellers['users'] as $seller ) {
$store_info = get_store_info( $seller->ID );
$store_url = get_store_url( $seller->ID );
}
( display content buttons here )
}
It is no longer working.
It there a proper to combine these 2 together ??
I am not too familiar with wordpress...
but could this be an issue with the $sellers variable?
I think the $sellers variable is not accessible from within your function.
Assuming $sellers is a global variable you could try:
add_action('userpro_after_profile_head','userpro_sc_bar', 99);
function userpro_sc_bar( $args ) {
global $userpro, $userpro_social, $sellers; // <-- Added $sellers
extract($args);
foreach ( $sellers['users'] as $seller ) {
$store_info = get_store_info( $seller->ID );
$store_url = get_store_url( $seller->ID );
}
( display content buttons here )
}
Ok, got is ,this works for me :
add_action('userpro_after_profile_head','userpro_sc_bar', 99);
function userpro_sc_bar( $args ) {
global $userpro, $userpro_social, $sellers; // <-- Added $sellers
extract($args);
$sellers = get_sellers(); // <-- Get $sellers
foreach ( $sellers['users'] as $seller ) {
$store_info = get_store_info( $seller->ID );
$store_url = get_store_url( $seller->ID );
}
( display content buttons here )
}

Categories