Define multiple values in php-function and use them within functions.php - php

Depending on the WordPress blog-URL, I need to define multiple variables (i.e. customer-group IDs). Some of the varaibles are integers and some are arrays. I want to use those variables in differnet functions within functions.php.
I need to know: is my solution good method, if I want to use multiple variables within different functions depending on the blog-URL?
I don’t want to use globals and constants don’t seem to work anymore in PHP-8 like they did in 7.2.
Function I - blog URL:
The variables change, depending on the blog URL. Function could look like this:
add_action( 'after_setup_theme', 'my_site_url' );
function my_site_url(){
$site_url = get_bloginfo('wpurl');
$stage_url = 'https://los.examplos.mx';
if ($site_url == $stage_url) {
/* - customer group ids for use in functions */
$wiederverkaeufer = 1234;
/* Versteckte Kategorien */
$hidecategory_wvk = [24, 863, 51, 87];
$return_array = [$wiederverkaeufer, $hidecategory_wvk];
} else {
/* - customer group ids for use in functions */
$wiederverkaeufer = 5678;
/* Versteckte Kategorien */
$hidecategory_wvk = [51, 48, 42];
$return_array = [$wiederverkaeufer, $hidecategory_wvk];
}
return $return_array;
}
Function II
Now I want to access those variables with some of the other functions within my functions.php. (This worked with constants before). For example
add_action( 'woocommerce_before_calculate_totals', 'cart_shipping_class_message', 20, 1 );
function cart_items_shipping_class_message( $cart ){
$my_ids = my_site_url();
$my_ids[0] = $wiederverkaeufer;
// Customer group current user
$group_id = BM_Conditionals::get_validated_customer_group();
// if is group "wiederverkaeufer" return
if ( $wiederverkaeufer == $group_id )
return;
//Do something
}
Function III: Test function:
I built a little test-function to check if I can call multiple variables and arrays from one function.
function my_shop_meldung(){
$a = "Moin";
$b = "Servus";
$c = "Hallo";
$d = ["22", "44", "55"];
$return_array = [$a, $b, $c, $d];
return $return_array;
}
function add_custom_text() {
?>
<div id="my_shopmeldung">
<?php
$my_results = my_shop_meldung();
$a = $my_results[0];
$b = $my_results[1];
$c = $my_results[2];
$d = $my_results[3][1];
//echo $a . $b . $c . $d;
echo $d;
?>
</div>
<?php
}
add_action('kt_beforeheader', 'add_custom_text', 10, 0);
I think this works as I could see the output "44" from the array.

Works for me:
This function shows product categories in WordPress Woocommerce, depending on the "MarketPress" customer group. Please note: this example will work only if you use the plugin Marketpress.
Function 1:
//add_action( 'wp_enqueue_scripts', 'my_site_url' );
add_action( 'after_setup_theme', 'my_site_url' );
function my_site_url(){
$site_url = get_bloginfo('wpurl');
//$site_url = get_home_url();
$stage_url = 'https://los.examplos.dk';
$stage_url_2 = 'https://los.examplos.dk';
//global $wiederverkaeufer, $hidecategory_wvk, $hidecategory_customer,
$boxkategorien, $gast_id, $kunde_id;
if ($site_url == $stage_url || $site_url == $stage_url_2 ) {
/* CONSTANTS - customer group ids for use in functions */
$wiederverkaeufer = 11111;
$gast_id = 22222;
$kunde_id = 33333;
/* Versteckte Kategorien */
$hidecategory_wvk = [11, 22, 33, 44];
$hidecategory_customer = [11, 22, 33, 44];
/* BOXEN */
$boxkategorien = = [11, 22, 33, 44];
} else {
/* CONSTANTS - customer group ids for use in functions */
$wiederverkaeufer = 3333;
$gast_id = 4444;
$kunde_id = 5555;
/* Versteckte Kategorien */
$hidecategory_wvk = = [11, 22, 33, 44];
$hidecategory_customer = = [11, 22, 33, 44];
/* BOXEN */
$box_kategorien = = [11, 22, 33, 44];];
}
$return_array = [
$wiederverkaeufer,
$gast_id,
$kunde_id,
$hidecategory_wvk,
$hidecategory_customer,
$boxkategorien
];
return $return_array;
}
Function II
Hide Woocommerce product categories depending on MarketPress customer group.
Vustomer group identified via "$group_id = BM_Conditionals::get_validated_customer_group();"
add_filter( 'get_terms', 'exclude_cats_from_shop', 10, 3 );
function exclude_cats_from_shop($terms, $taxonomies, $args ){
if ( is_admin() && ! defined('DOING_AJAX') )
return $terms;
$group_id = BM_Conditionals::get_validated_customer_group();
//get the customer group ID of current user
$customer_group = my_site_url();
//call function my_site_url(), get the array, and save to $customer_group
$wiederverkaeufer = $customer_group[0];
//save customer group id to $wiederverkaeufer
$hidecategory_wvk = $customer_group[3];
$hidecategory_customer = $customer_group[4];
//get those product group ids
if ( $wiederverkaeufer == $group_id ){
//if wiederverkaeufer
$new_terms = array();
//$hide_category_wvk = HIDECATEGORY_WVK;
// Ids der Produktkategorien die ausgeschlossen werden sollen
if ( in_array( 'product_cat', $taxonomies ) && is_shop() || is_product() ) {
foreach ( $terms as $key => $term ) {
if ( ! in_array( $term->term_id, $hidecategory_wvk ) ) {
$new_terms[] = $term;
}
}
$terms = $new_terms;
}
return $terms;
}// Ende ist Wiederverkaeufer
// if is customer group customer
else {
$new_terms = array();
// hide productcategories
if ( in_array( 'product_cat', $taxonomies ) && is_shop() || is_product() ) {
foreach ( $terms as $key => $term ) {
if ( ! in_array( $term->term_id, $hidecategory_customer ) ) {
$new_terms[] = $term;
}
}
$terms = $new_terms;
}
return $terms;
}
} //End

Related

Dynamically added custom fields not displayed on WooCommerce email notifications

I have a different kind of scenario then the typical custom fields (I suppose). I am not getting custom values (fields) from user in the form rather I have an implementation which adds:
ColorName
Size
City
These are from a custom product flow which adds custom attributes to the cart, here is how I am doing that:
add_action('wp_ajax_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
add_action('wp_ajax_nopriv_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
function wdm_add_user_custom_data_options_callback()
{
// print_r($_POST);
$productIDM = $_POST['product_id'];
// case swith
switch ($productIDM) {
case "Ace Dura Silk":
$productID = 3254;
break;
case "Ace Matt Finish":
$productID = 3232;
break;
case "Ace Plastic Emulsion":
$productID = 3276;
break;
case "Ace Weather Defender":
$productID = 2991;
break;
case "Overall Plasticoat":
$productID = 3112;
break;
}
$colorname = $_POST['colorname'];
$cityname = $_POST['cityname'];
$size = $_POST['size'];
$price = $_POST['price'];
global $woocommerce;
$woocommerce->cart->add_to_cart( $productID, 1 );
// die();
// echo 'I am in...';
$result = array(
'status' => true
);
echo json_encode($result);
}
add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,10);
function wdm_add_item_data($cart_item_data, $product_id) {
global $woocommerce;
$new_value = array();
$new_value['_custom_options'] = $_POST['custom_options'];
if(empty($cart_item_data)) {
return $new_value;
} else {
return array_merge($cart_item_data, $new_value);
}
}
add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
function wdm_get_cart_items_from_session($item,$values,$key) {
if (array_key_exists( '_custom_options', $values ) ) {
$item['_custom_options'] = $values['_custom_options'];
}
return $item;
}
add_filter('woocommerce_cart_item_name','add_usr_custom_session',1,3);
function add_usr_custom_session($product_name, $values, $cart_item_key ) {
$return_string = $product_name . "<div class='cart_subitems_custom'><br /><small>".$values['_custom_options']['colorname']."</small><br /><small>".$values['_custom_options']['cityname']."</small><br /><small>".$values['_custom_options']['size']."</small></div>" ; //. "<br />" . print_r($values['_custom_options']);
return $return_string;
}
add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
function wdm_add_values_to_order_item_meta($item_id, $values) {
global $woocommerce,$wpdb;
wc_add_order_item_meta($item_id,'_colorname',$values['_custom_options']['colorname']);
wc_add_order_item_meta($item_id,'_cityname',$values['_custom_options']['cityname']);
wc_add_order_item_meta($item_id,'_size',$values['_custom_options']['size']);
}
add_action( 'woocommerce_before_calculate_totals', 'update_custom_price', 1, 1 );
function update_custom_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $cart_item_key => $value ) {
// Version 2.x
//$value['data']->price = $value['_custom_options']['custom_price'];
// Version 3.x / 4.x
if($value['_custom_options']['price'] == null){
echo"";
}else{
$value['data']->set_price($value['_custom_options']['price']);
}
}
}
I am getting these custom values almost everywhere except Email Notification.
Here is what normal product order edit shows:
Here is how I am getting the custom product in order edit page:
I have tried all the solution I can possibly find (filter & action hooks) but nothing works for me.
I have tried first answer from this:
add_action( 'woocommerce_checkout_create_order_line_item', 'custom_checkout_create_order_line_item', 20, 4 );
function custom_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
if( isset( $values['colorname'] ) )
$item->add_meta_data( __('DCM Shade'), $values['_colorname'] );
}
Also the common method I found everywhere:
function custom_woocommerce_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
// Get meta
$color = $order->get_meta( 'colorname', true );
// NOT empty
if( ! empty( $color ) ) {
$fields['colorname'] = array(
'label' => __( 'Shade' ),
'value' => $color,
);
}
// Get (other) meta
$shipping_email = $order->get_meta( '_cityname', true );
// NOT empty
if ( ! empty( $shipping_email ) ) {
$fields['_cityname'] = array(
'label' => __( 'City' ),
'value' => $shipping_email,
);
}
return $fields;
}
add_filter( 'woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3 );
But I can't get the custom fields.
What am I doing wrong can please anyone please guide me.

How to display only specific category label/name on page and hide other categories name?

I am trying to display only 1 category name and want to hide other categories name in post listing page.
add_filter('get_the_terms', 'hide_categories_terms', 10, 3);
function hide_categories_terms($terms, $post_id, $taxonomy){
$excludeIDs = array(1,322,320,321);
// get all the terms
$exclude = array();
foreach ($excludeIDs as $id) {
$exclude[] = get_term_by('id', $id, 'category');
}
// filter the categories
if (!is_admin()) {
foreach($terms as $key => $term){
if($term->taxonomy == "category"){
foreach ($exclude as $exKey => $exTerm) {
if($term->term_id == $exTerm->term_id) unset($terms[$key]);
}
}
}
}
return $terms;
its hiding all the categories name but not showing the category name that I wanted to display it. Kindly help me out
You should be able to do this w/o have to get the exclude terms or the double loops:
add_filter('get_the_terms', 'hide_categories_terms', 10, 3);
function hide_categories_terms($terms, $post_id, $taxonomy){
if ( ! is_admin() && is_single() ) {
// filter for terms that are not in the exclude array
$filtered_terms = array_filter($terms, function($term) {
$excludeIDs = array(1, 322, 320, 321);
return ! in_array($term->term_id, $excludeIDs);
});
// return filtered array of terms
return $filtered_terms;
}
// return default terms JIC the above case is not met
return $terms;
}
Another way you could write this to save some lines, if you are running PHP 7.4+:
add_filter('get_the_terms', 'hide_categories_terms', 10, 3);
function hide_categories_terms($terms, $post_id, $taxonomy){
if ( ! is_admin() && is_single() ) {
$excludeIDs = [1, 322, 320, 321];
// filter for terms that are not in the exclude array
$filtered_terms = array_filter($terms, fn($t) => ! in_array($t->term_id, $excludeIDs));
// return filtered array of terms
return $filtered_terms;
}
// return default terms JIC the above case is not met
return $terms;
}

Get an order item custom index and assign it to options value In Woocommerce

I use Woocommerce latest version 3.4.2.
In this case, we collect the order data: the product and its additives ( I take in meta data).
How to assign the index of variable $skus[] = $product->get_sku(); as the value of variable $product_mod[] = '';?
$product_mod[1] = "0"; // The product ( ingredient Sugar) with key 1 is the product modifier with key 0.
// Get product details
$skus = $item_quantities = $line_item_totals = $product_mod = array();
// Loop though order items
foreach( $order->get_items() as $item_id => $item){
$product_id = $item->get_product_id();
$product = $item->get_product();
$item_quantities[] = $item->get_quantity();
$line_item_totals[] = $item->get_total();
$skus[] = $product->get_sku();
$product_mod[] = NULL;
$ai = $item->get_meta('Optionally select');
if( strpos( $ai, 'Cinnamon' ) !== false ) {
$skus[] = '10001';
$item_quantities[] ='1';
$line_item_totals[] = '50';
$product_mod[] = '';
}
if( strpos( $ai, 'Sugar' ) !== false ) {
$skus[] = '10002';
$item_quantities[] ='1';
$line_item_totals[] = '50';
$product_mod[] = '';
}
if( strpos( $ai, 'Mint' ) !== false ) {
$skus[] = '10003';
$item_quantities[] ='1';
$line_item_totals[] = '50';
$product_mod[] = '';
}
}
// Product details
foreach ($skus as $key => $value){
$data .= "&product_sku[".$key."]=".$value."";
$data .= "&product_quantity[".$key."]=".$item_quantities[$key]."";
$data .= "&product_price[".$key."]=".$line_item_totals[$key]."";
if( isset($product_mod[$key]) ) {
$data .= "&product_mod[".$key."]=".$key."";
}
}
print_r( $data ); now show:
// For the convenience of reading, I wrote in a column, but this is a string.
&product_sku[0]=10030
&product_quantity[0]=1
&product_price[0]=499
&product_sku[1]=10002
&product_quantity[1]=1
&product_price[1]=50
&product_mod[1]=1
Need:
&product_sku[0]=10030 // Coffe sku
&product_quantity[0]=1 // Coffe quantity
&product_price[0]=499 // Coffe price
&product_sku[1]=10002 // Sugar sku
&product_quantity[1]=1 // Sugar quantity
&product_price[1]=50 // Sugar price
&product_mod[1]=0 // Ingredient Sugar with number 1, is a product modifier with number 0.
I think this is right way:
You have been complicating a bit the thing… You need to set the main order item index in a variable to get it for your product modifier in the selected additional options. No need of any complications…
I have revisited, simplified and compacted your code:
// Array of defined options ( sku => option name )
$options = array(
'10001' => 'Cinnamon',
'10002' => 'Sugar',
'10003' => 'Mint',
);
$count = 0;
// Loop though order items
foreach( $order->get_items() as $item_id => $item){
$product_id = $item->get_product_id();
$product = $item->get_product();
$data .= '&product_sku['.$count.']='.$product->get_sku();
$data .= '&product_quantity['.$count.']='.$item->get_quantity();
$data .= '&product_price['.$count.']='.$item->get_total();
$ind = $count; // Here we set the main order item index in a variable
$count++;
// Get order item selected options
$options_selected = $item->get_meta('Optionally select');
// Loop though order items selected options
foreach( $options as $sku_key => $label_value ){
if( strpos( $options_selected, $label_value ) !== false ) {
$data .= '&product_sku['.$count.']='.$sku_key;
$data .= '&product_quantity['.$count.']=1';
$data .= '&product_price['.$count.']=50';
$data .= '&product_mod['.$count.']='.$ind;
$count++;
}
}
}
// Testing output
print_r( $data );
Untested, but it should work as expected.
Just make a class. That's what they are made for.
That way you will always have your data neatly grouped together the way you want it without the messiness of having to remain an order or multiple arrays.
The class below is just a proof of concept, getters and setters you'll have to make yourself, but if you do it like this, you have control of the data, where it goes, what belongs with what, and you can even move data from one array to another or copy the objects over.
What you do is make your own object that has the product data you want.
Then you add an array in it "extras" where you can "extras" to the product.
Then you add a function to count the total of "own price + price of extras"
And some other helper functions you need.
Then you wrap it up and have a nice class to help you.
Please note, it's pseudo code, will need some work.
class ProductData
{
protected $product_id;
protected $product;
protected $quantity;
protected $total;
protected $sku;
protected $extras = [];
public function __construct($product_id, $product, $sku, $total, $quantity)
{
$this->product_id = $product_id;
$this->product = $product;
$this->sku = $sku;
$this->total = $total;
$this->quantity = $quantity;
}
public function addExtra($product)
{
$this->extras[] = $product;
}
public function getTotal()
{
$total = $this->total;
foreach($this->extras as $extra) {
$this->total += $extra->getTotal();
}
return total;
}
public static function fromItem($item)
{
$product = new self(
$item->get_product_id(),
$item->get_product(),
$item->get_sku(),
$item->line_item_totals(),
$item->get_quantity()
);
return $product;
}
}
$preregistered_extras = [
'Cinnamon' => new Product(
wc_get_product_id_by_sku('10001'),
wc_get_product(wc_get_product_id_by_sku('10001')),
'10001',
'50',
'1'),
'Sugar' => new Product(
wc_get_product_id_by_sku('10002'),
wc_get_product(wc_get_product_id_by_sku('10002')),
'10002',
'50',
'1'),
'Mint' => new Product(
wc_get_product_id_by_sku('10003'),
wc_get_product(wc_get_product_id_by_sku('10003')),
'10003',
'50',
'1'),
];
$product_list = [];
foreach( $order->get_items() as $item_id => $item){
$product = Product::fromItem($item);
$ai = $item->get_meta('Optionally select');
foreach($preregistered_extras as $name => $extra) {
if( stripos( $ai, $name ) !== false ) {
$product->addExtra($extra);
}
}
}
var_dump($product_list);
$total = 0;
foreach($product_list as $item) {
$total += $item->getTotal();
}
echo "Total = $total";

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 orders page add customer role custom column

I want to add column to show the customer role on the WooCommerce orders, I search and everything I found is for one user. I also found this code on this link (WooCommerce show custom column) but I do not understand where I put what I need.
I also found this code (https://gist.github.com/corsonr/5975207)
but I do not managed to get the user role.
I added $user_role = $user->roles;
and
switch ($column)
{
case "user_role":
echo $user_role;
break;
}
but it not worked, I know it is array but use of [0] or [1] did not work.
I missing something?
It is possible to do what I what?
Add below code in your theme functions.php
add_filter('manage_edit-shop_order_columns', 'add_column_heading', 20, 1);
function add_column_heading($array) {
$res = array_slice($array, 0, 2, true) +
array("customer_role" => "Customer Role") +
array_slice($array, 2, count($array) - 1, true);
return $res;
}
add_action('manage_posts_custom_column', 'add_column_data', 20, 2);
function add_column_data($column_key, $order_id) {
// exit early if this is not the column we want
if ('customer_role' != $column_key) {
return;
}
$customer = new WC_Order( $order_id );
if($customer->user_id != ''){
$user = new WP_User( $customer->user_id );
if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
foreach ( $user->roles as $role )
echo $role;
}
}
}

Categories