how to get the cartesian index of variants

I have variants in a product page – every property has 2 variants for example

size : 40, 41

color : red, yellow

shape : circle, triangle

when I click on radio inputs I get the indices of the checked inputm for example [0,1,0]

So the question is how to make cartesian indices and then find the index using

$index = array_search($indices, $cartesian);

This is the screen shot of variants:

Drawing Sparklines Programmatically in Laravel Excel using maatwebsite/excel Package

I am working on a Laravel project and utilizing the maatwebsite/excel package to export Excel files. In my Excel file, I have a dataset that I want to represent using sparklines. The maatwebsite/excel package provides various features for exporting data to Excel, but I couldn’t find any specific information on how to draw sparklines programmatically through PHP.

I have already explored the package’s official documentation (https://docs.laravel-excel.com/3.1/getting-started/installation.html), but it doesn’t seem to cover sparkline integration. Is there a way to generate sparklines programmatically using PHP within or outside the context of maatwebsite/excel package? If so, could you provide an example or guide me on how to achieve this?

enter image description here

I appreciate any insights or code examples that demonstrate the process of creating sparklines inside the cells of an Excel file using the maatwebsite/excel package and Laravel.

Thank you!

Problem with PHP shortcode cutting wordpress title

I have tinkered a small PHP code that automatically outputs all posts of the currently displayed category to me via shortcode (except the currently displayed post). So far so good, now my titles are always built the same way “87 lorem ipsum – lorem ipsum”. The code now cuts away the number as intended, but not the text behind the “-“.

Website is: sprueche-fuer-dich.de

Code:

function show_cat_posts_func( $atts ) {
global $post;

$url_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$url_segments = explode('/', trim($url_path, '/'));
$category_from_url = isset($url_segments[0]) ? $url_segments[0] : '';

$a = shortcode_atts( array(
    'category' => $category_from_url, 
), $atts );

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category_name' => $a['category'],
    'posts_per_page' => -1,
    'orderby' => 'title', 
    'order' => 'ASC', 
    'post__not_in' => isset($post) ? array($post->ID) : array(),
);

$the_query = new WP_Query( $args );

$output = '';
if ( $the_query->have_posts() ) {

    $output .= '<p class="sidebar-heading-txt">' . $a['category'] . '</p>';

    $output .= '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        $title = get_the_title();
        $title = substr($title, 3);
        $title = explode('–', $title)[0];
        $output .= '<li class="sidebar-small-txt"><a href="' . get_permalink() . '">' . $title . '</a></li>';
    }
    $output .= '</ul>';
} else {
    $output .= '<p>Keine Beiträge in dieser Kategorie gefunden.</p>';
}

wp_reset_postdata();

return $output;
}
add_shortcode( 'show_cat_posts', 'show_cat_posts_func' );'

How to remove vendor from Customer booking cancelled email

I am using WooCommerce Bookings. I’ve customized the customer-bookings-cancelled template and it works when a customer cancels a booking, but it is sending an email notification to both vendor and customer. I need to remove the vendor from this notification but cannot find any instruction on how to do this. Are there any classes or hooks I can use to strip the vendor from the notification.

// Hook into the 'woocommerce_email_recipient_customer_booking_cancelled' filter
add_filter( 'woocommerce_email_recipient_customer_booking_cancelled', 'custom_exclude_vendor_from_customer_email', 10, 2 );

function custom_exclude_vendor_from_customer_email( $recipient, $booking ) {
    // Get the customer email
    $customer_email = $booking->get_customer_email();

    // Get the vendor email(s) - Replace 'vendor' with the appropriate user role for your vendors
    $vendor_emails = array();
    $vendors = get_users( array( 'role' => 'vendor' ) );
    foreach ( $vendors as $vendor ) {
        $vendor_emails[] = $vendor->user_email;
    }

    // Remove vendor emails from the recipient list
    $recipient_emails = array_diff( array( $customer_email ), $vendor_emails );

    // Return the filtered recipient list (customer email only)
    return $recipient_emails;
}

Any direction here would be greatly appreciated.

Yii3 and Docker: how to install and run a project

i know that Yii3 is in developing, but i want to try and explore it.
I want to install it and run with Docker but i’ve never used Docker so i’m in difficult:
How can i install Yii3 and run it using Docker in Windows 10?

At the moment i had only execute:
composer create-project yiisoft/app –prefer-dist –stability=dev your_project

Thanks in advance
ps: please write all steps from start to end

woocommerce attribute terms – save custom field value

Can anyone help? I created a custom field on attribute term but don’t know why it is not saving after the term update. User has necessary permissions.

if (is_admin() && isset($_GET['taxonomy'], $_GET['post_type']) && $_GET['post_type'] === 'product') {

$taxonomy_name = sanitize_text_field($_GET['taxonomy']);


add_action($taxonomy_name . '_edit_form_fields', 'custom_edit_term_fields', 10, 2);

function custom_edit_term_fields($term, $taxonomy)
{

    $value = get_term_meta($term->term_id, 'custom-term-input', true);

    echo '<tr class="form-field">
<th>
    <label for="custom-term-input">Custom input</label>
</th>
<td>
    <input name="custom-term-input" id="custom-term-input" type="text" value="' . esc_attr($value) . '" />
    <p class="description">Description text</p>
</td>
</tr>';
}


add_action('created_' .  $taxonomy_name, 'custom_save_term_fields');
add_action('edited_' .  $taxonomy_name, 'custom_save_term_fields');

function custom_save_term_fields($term_id)
{

    update_term_meta(
        $term_id,
        'custom-term-input',
        sanitize_text_field($_POST['custom-term-input'])
    );
}
}

WordPress blog page does not use css

I have set up simple wordpress page. Simple gallery, few forms and that’s it. I decided to set up a simple blog page so I created a new page in wordpress and in reading settings I made it to be a posts page.

Now the problem is that this page does not use any styles. This is how it looks at the moment: https://nsjtomaszowlub.pl/galeria/aktualnosci/ . For refference here is regular page on this website: http://nsjtomaszowlub.pl/galeria/kalendarz-inicjatyw-duszpasterskich-2023/ .

I have checked in WordPress template hierarchy that it should inherit everything from index.php and actually it does contain html from index.php file, however without css. Please help me to fix this issue.

preserving 0’s after decimal point while displaying Currency in Indian Numbering Format in PHP

I need to display ‘150000.50’ in Indian number format with the last zero intact.

I followed the following, but the solution
Previous answer doesn’t completely solve the issue.

1.

preg_replace("/(d+?)(?=(dd)+(d)(?!d))(.d+)?/i", "$1,", $num);
 // Output: 1,50,000.5 
// Expected output: 1,50,500.50
new NumberFormatter($locale = 'en_IN', NumberFormatter::DECIMAL); from Intl extension.
// Output: 1,50,000.5
// Expected output: 1,50,500.50

money_format is now deprecated. If anyone can update preg_replace function regex to preserve the trailing zero, it will be helpful.

Getting error message shipping options not avaliable

Code that I am using giving errorI have added this code still getting error in checkout page and can’t move to paypal. How to remove it.

add_filter( ‘woocommerce_checkout_fields’, ‘remove_shipping_validation_for_variable_products’ );

function remove_shipping_validation_for_variable_products( $fields ) {
// Enter the product IDs of the variable products for which you want to remove shipping validation
$product_ids = array( 1932, 1923, 1913 );

if ( ! empty( WC()->cart ) ) {
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];

        if ( in_array( $product_id, $product_ids ) ) {
            unset( $fields['shipping']['shipping_country']['validate'] );
            unset( $fields['shipping']['shipping_state']['validate'] );
            unset( $fields['shipping']['shipping_city']['validate'] );
            unset( $fields['shipping']['shipping_address_1']['validate'] );
            unset( $fields['shipping']['shipping_postcode']['validate'] );
            break; // Stop the loop after finding the first matching product
        }
    }
}

return $fields;

}

Still getting error message There are no shipping options available. Please ensure that your address has been entered correctly, or contact us if you need any help.

How to remove it for set of products id.

How to send in axios post request multiple datas in javascript and get the datas in php

Language used : JS with React and PHP with Laravel

Resume : After posting an order, I need to send a mail (sendEmailToReferent). I need to pass multiple data from different array/object.

Problem : When I pass the multiple datas I only get the array, but the object is transformed into an empty array.

To know :

  • If I only pass “formData” without “allUsers” in my axios request it’s working.
  • Log of formData in sendEmailToReferent before post request give me my object
  • Log of allUsers in sendEmailToReferent before post request give me my array
  • Log of res (return response()->json($request);) in sendEmailToReferent give me

allUsers :
(5) [{…}, {…}, {…}, {…}, {…}]
formData: [] (here empty array)

Here is the onSubmit to post Order function where i get all my datas :

const allUsers = useSelector((state) => state.user?.usersData);

 const onSubmit = (data) => {
    const datas = data.internOrders;
    const formData = new FormData();

    formData.append('businessUnit', datas.businessUnit);
    formData.append('object', datas.object);
    formData.append('userData', JSON.stringify(userData));
    dispatch(postInternOrder(formData, allUsers));
  };

Then, in my post axios request, i dispatch the sendEmailToReferent with my datas

export const postInternOrder = (formData, allUsers) => async (dispatch) => {
  dispatch(setLoading(true));
  try {
    await axios({
      method: 'post',
      url: `${process.env.REACT_APP_API_URL}api/order/intern`,
      data: formData,
    }).then((res) => {
      console.log(res);
      const userData = res.data;
      dispatch(sendEmailToReferent(formData, allUsers));
    });
  } catch (err) {
    console.log(err);  }
};

my sendEmailToReferent request

export const sendEmailToReferent =
  (formData, allUsers ) =>
  async (dispatch) => {
    console.log(formData); 
    try {
      axios({
        method: 'post',
        url: `${process.env.REACT_APP_API_URL}api/mail/referent/toValidate`,
        data: { formData, allUsers },
        allUsers,
      }).then((res) => {
        console.log(res);
      });
    } catch (err) {
      console.log(err);
    }
  };

And then, my laravel function to send a mail

 public function NOneReceivedOrder(Request $request)
        {
            return response()->json($request);

            $orderDatas = $request->get('formData');
    
            $allUsers =  $request->get('allUsers');
    
            $oneOrder = InternOrders::where('IdSP', $orderDatas['idSP'])->first();
    
            $userDatas = json_decode($orderDatas['userData']);
    
            $referent = $orderDatas['referent'];
            $referentDatas = collect($allUsers)->where('displayName', $referent)->first();
    
            Mail::send('ReferentReceivedNewOrderMail',  ['referentDatas' => $referentDatas, 'oneOrder'  => $oneOrder, 'orderDatas' => $orderDatas], function ($m) use ($userDatas, $referentDatas, $orderDatas) {
                $m->from($userDatas->email);
                $m->to($referentDatas->email);
                $m->subject('TEST');
            });
        }

What I have already tried :

  • Change the way to get the datas in laravel ($orderDatas = json_decode($request['formData']);)

  • Change the way to send datas in js (dispatch(sendEmailToReferent(formData : {formData}, allUsers))

  • join the data into an object

     const requestData = {
            formData: formData,
            allUsers: allUsers,
          };
          axios({
            method: 'post',
            url: `${process.env.REACT_APP_API_URL}api/mail/referent/toValidate`,
            data: requestData,
    

And getting the datas in laravel :

$requestData = $request->all();

        $orderDatas = $requestData('formData');
        $allUsers = $requestData['allUsers'];

but got error “Trying to access array offset on value of type null”

How to use function’s default parameter in PHP

I want to do something like this.

function add($num1, $num2 = 1) {
    return $num1 + $num2;
}

$bool = true; // Can be true or false

if($bool) {
    add(5, 5);
} else {
    add(5);
}

I was asking me, if it is possible to write this logic in one line like, without repeating the default value:

add(5, $bool ? 5 : USE_DEFAULT_PARAMETER);

Dynamic loading of modal window in WordPress

There is a block with modal windows, in which there are containers that are modal windows.
On the page there are buttons with data-path attribute containing data-target of modal window container.

Example:

<button data-target="order-1">Open order-1 Modal</button>

<button data-target="order-2">Open order-2 Modal</button>

<div class="modal">
    <div class="modal__container" data-target="order-1">
      content 
    </div>
    <div class="modal__container" data-target="order-2">
      content 
    </div>
</div>

By clicking on the button with the corresponding data-path of the modal window data-target, it is opened.

So, it is necessary to load the necessary modal window if there is a button on the WordPress page with the corresponding data-path attribute

Tried through js to check the entire page for the presence of buttons with data-path attribute and add to the body classes and in wp to perform the necessary operations, if get_body_class() has these classes, but this method does not work because js triggers later than php and in get_body_class() these classes do not appear.

Sending JavaScript array to Php with ajax not working

I am trying to send the content of a JavaScript array to a different page using $.post, but it doesn’t work – the coreresponding $_POST is not set…

Can someone explain me what’s wrong ?

Here is the js code, on page 1:

<script type="text/javascript">
    var i = sessionStorage.length;
    var categoriesTab = [];
    for (let j = 0; j < i; j++) {
        if (sessionStorage.getItem(sessionStorage.key(j)) == 'active') {
            categoriesTab.push(sessionStorage.key(j));
        }
    }
    const liste = document.getElementById('liste');
    liste.addEventListener('click', function (event){
        event.preventDefault();
        if (window.location.href == 'https://dom.fr/page1/'){
            $.post(
                'page2.php',
                {
                    categoriesActives : categoriesTab
                }
            )
        }
        window.location.assign('https://dom.fr/page2/');
    });
</script>

The categoriesTab variable is set and everything seems to work.
But when I get to page 2, $_POST is empty… :

<?php

$array = [];

if (isset($_POST['categoriesActives'])) {
    $array = $_POST['categoriesActives'];
} else {
    $array = ['a', 'z', 'e', 'r'];
}

?>```


In export pdf link is not showing properly

I am working on a project in which I am using a HTML template to generate the PDF report. In some reports I need to show some demo link to show the process. Below is a demo in which I am showing the link to download profit.
In HTML template, I am using below code to show link

<p>https://mywebsiteurl.com/v2/testReport.php?report_type=type&reference=<b>reference_number</b>&usercode=<b>user_code</b>&currency=<b>usd</b>&countrycode=<b>us</b>&reportdatefrom=<b>report_date_from</b>&reportdateto=<b>report_date_to</b>&reportforcountry=<b>report_for_country</b></p>

I am getting the below output
enter image description here

Parameter in bold need to replaced by dynamic values.
In the output I want that

  • URL must take max 3 lines.
  • testReport.php must not spit in 2 lines.

I don’t understand why is testReport not come in a single line? Any idea to achieve it

how to print google translated page in jquery

I am using Google Translate plugin on my site. I want to print the translated page of my website created with PHP. I am using ajax to call the formatted page from a php file to print. However, the ajax result of the page is in default English language. I tried passing googletrans variable to the page and setting the cookie for the page before it gave the call back result to ajax. And then print using document.write. But the print is always coming in English. Is it not possible to print translated by google in jquery ?

If required I can add more details here.