Gift in cart for order amount in Woocommerce

I need a code that with 150 subtotal add a gift in cart. I have the following code:
`

/** Gift in Cart */
// Add free gifted product for specific cart subtotal
add_action( 'woocommerce_before_calculate_totals', 'check_free_gifted_product' );
function check_free_gifted_product( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Settings
    $free_product_id   = 7912;
    $targeted_subtotal = 150;

    $cart_subtotal     = 0; // Initializing

    // Loop through cart items (first loop)
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
        // When free product is is cart
        if ( $free_product_id == $cart_item['product_id'] ) {
            $free_key = $cart_item_key;
            $free_qty = $cart_item['quantity'];
            $cart_item['data']->set_price(0); // Optionally set the price to zero
        } else {
            $cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
        }
    }

    // If subtotal match and free product is not already in cart, add it
    if ( ! isset($free_key) && $cart_subtotal >= $targeted_subtotal ) {
        $cart->add_to_cart( $free_product_id );
    }
    // If subtotal doesn't match and free product is already in cart, remove it
    elseif ( isset($free_key) && $cart_subtotal < $targeted_subtotal ) {
        $cart->remove_cart_item( $free_key );
    }
    // Keep free product quantity to 1.
    elseif ( isset($free_qty) && $free_qty > 1 ) {
        $cart->set_quantity( $free_key, 1 );
    }
}

`

When I apply a discount and the subtotal of order is less than subtotal targeted the gift is removed by the order in checkout but the gift should remain also if I apply a discount.

I modify the code in this way but it doesn’t work:

`

add_action( 'woocommerce_before_calculate_totals', 'check_free_gifted_product' );
function check_free_gifted_product( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Settings
    $free_product_id   = 7912;
    $targeted_subtotal = 150;

    $cart_subtotal     = 0; // Initializing
    $applied_coupons   = WC()->cart->get_applied_coupons(); // Get applied coupon codes
    $free_product_in_cart = false; // Flag to check if free product is in cart

    // Loop through cart items (first loop)
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
        // When free product is is cart
        if ( $free_product_id == $cart_item['product_id'] ) {
            $free_product_in_cart = true;
            $free_qty = $cart_item['quantity'];
            $cart_item['data']->set_price(0); // Optionally set the price to zero
        } else {
            $cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
        }
    }

    // Store the original cart subtotal before applying the coupon discounts
    $original_subtotal = $cart_subtotal;

    // Loop through applied coupon codes and apply discounts to the cart subtotal
    foreach ( $applied_coupons as $code ) {
        $coupon = new WC_Coupon( $code );
        $discount_amount = $coupon->get_discount_amount( $cart_subtotal );
        $cart_subtotal -= $discount_amount;
    }

    // If original subtotal match and free product is not already in cart, add it
    if ( ! $free_product_in_cart && $original_subtotal >= $targeted_subtotal ) {
        $cart->add_to_cart( $free_product_id );
    }
    // If original subtotal doesn't match and free product is already in cart, remove it
    elseif ( $free_product_in_cart && $original_subtotal < $targeted_subtotal ) {
        $cart->remove_cart_item( $free_product_id );
    }
    // Keep free product quantity to 1.
    elseif ( $free_product_in_cart && $free_qty > 1 ) {
        $cart->set_quantity( $free_product_id, 1 );
    }
}

`

Cors ‘Redirect is not allowed for a preflight request.’

POST with API-TOKEN does not work

GET with API-TOKEN works, normal POST and GET also works. Stops working when I try to send POST together with token and data. I also tried not using localhost from https://rynokua.com

Fetch:

      const response = await fetch(`${this._apiBase}cars/add`, {
            method: 'POST',
            headers: {
                'X-API-TOKEN': this._apiHeaders.tokenApi,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                city_id: data.city,
                color_id: 39,
                category_id: data.category,
                body_id: data.body,
                fuel_id: data.fuel,
                drive_id: data.drive,
                race: data.race,
                description: data.aboutPost,
                gearbox_id: data.gearbox,
            }),
        })

cakephp application.php

  ->add(function ($request, $response, $next) {
                $http_origin = '*';
                if (isset($_SERVER['HTTP_ORIGIN']))
                    $http_origin = $_SERVER['HTTP_ORIGIN'];
                else {
                    if (isset($_SERVER['HTTP_REFERER'])) {
                        $http_origin = $_SERVER['HTTP_REFERER'];
                    }
                }
                if ($http_origin == "https://rynokua.com" || $http_origin == "http://localhost:3000") {
                    return $next($request, $response)
                        ->withHeader('Access-Control-Allow-Origin', $http_origin)
                        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
                        ->withHeader('Access-Control-Allow-Headers', 'X-API-TOKEN, content-type')
                        ->withHeader('Access-Control-Allow-Type', 'application/json');
                }
                return $next($request, $response);
            }

error:

Access to fetch at ‘https://api.rynokua.com/api/cars/add’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: Redirect is not allowed for a preflight request.
post-service.js:7
POST https://api.rynokua.com/api/cars/add net::ERR_FAILED

Browser

WordPress site issue when moving PHP version from 7.4 to 8.0

I have WP site (SAFE4YOU) that specializes in insurance that hosting now on “SiteGround” with PHP 7.4 version.

Im trying to migrate that site to “Kinsta” servers but there the earliest PHP version is 8.0 so I have to change the site to that version.

after I migrate the site all looks great except one page, the calculator pricing page : https://safe4you.kinsta.cloud/calculator/main-calculator/

the problem is, after I choose destination and date (first screen), and after I chose ages (second screen) the system needs to trow the results (third screen) and seems its not working.

safe4you calculator issue

on error.log:

2022/12/27 08:37:51 [error] 72560#72560: *6310 FastCGI sent in stderr: "PHP message: PHP Warning: Undefined array key "days_2" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 145PHP message: PHP Warning: Undefined array key "days_2" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 184PHP message: PHP Warning: Undefined array key "option_to_person" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 308PHP message: PHP Warning: Undefined array key "days_2" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 145PHP message: PHP Warning: Undefined array key "days_2" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 184PHP message: PHP Warning: Undefined array key "option_to_person" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 308PHP message: PHP Warning: Undefined array key "days_2" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 145PHP message: PHP Warning: Undefined array key "days_2" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 184PHP message: PHP Warning: Undefined array key "option_to_person" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 308PHP message: PHP Warning: Undefined array key "days_2" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 145PHP message: PHP Warning: Undefined array key "days_2" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 184PHP message: PHP Warning: Undefined array key "option_to_person" in /www/safe4you_296/public/wp-content/themes/hello-theme-child-master/functions.php on line 308PHP message: PHP Warning: Undefined array key "days_2" in /www/safe4you_296/public/wp-content/themes/hello-the

functions.php lines:
145 –

 $total_days_trip = $_COOKIE['days_2'] ? $_COOKIE['days_2'] : $_COOKIE['days'];

184 –

        $results[$company_id]['total_days'] = $post_form['days_2'] ? absint($post_form['days_2']) : absint( $post_form['days'] );

308 –

         if($post_form['option_to_person']){ // If in form data have at least 1 extension.

Im trying to change with “Kinsta” support manually the PHP version to 7.4 and they cant keep it because they dont give support for that version. when I changed the version all looks great.

I notice that all the error that came from function.php line have cookies/form data in common.

what I expecting:
if you go into that page : https://safe4you.co.il/calculator/main-calculator/
choose destination and date, after that choose passengers ages, and after that all the results need to displayed like on the image.

safe4you calculator expecting

its really weird. anyone can help?

PHP: CURL not showing any response after 10 minute or more time

When I’m trying to send data on a API using CURL. API taking long time (10 minute or more) to the execution and at the end API successfully executed on its destination. but After the 10 minute, curl not returning any response.

But same process are complete in under the 5 minutes, then everything is working fine.

Here is my code

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt_array($ch, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "postvar1=value1",
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/x-www-form-urlencoded",
  ),
));
$api_res = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
$api_obj = json_decode($api_res, true);

Please suggest me the better solution for successfully run this script after 10 minute or more time.

how to sum tow $row echo results and show in text box

i need to sum two echo values that fetch by data base according to a specific id.i need to sum the value that i get from database sql (id=”soil_value_id” and id=”land_extent_id” ) it have to be automatically showing in a text box . please help me thank you ЁЯЩВ


                
                
<?php 
$con = mysqli_connect("localhost","root","","loan_db");
                                  
 {
$stud_id = $_POST['borrower_id']  ;

$query = "SELECT * FROM borrowers WHERE id='$stud_id' ";
$query_run = mysqli_query($con, $query);

if(mysqli_num_rows($query_run) > 0)
{
foreach($query_run as $row)
                                            
{
 ?>
                                                
                                                    
                                                    

<label for=""style="color: #1b78c9"><b> soil type value  </b></label>
<input type="number" id="soil_value_id" value="<?= $row['soil_value']; ?>" disabled/>
                                              

<label for=""style="color: #1b78c9"><b>  land extent </b></label>
<input type="number" id="land_extent_id" value="<?= $row['land_extent']; ?>" disabled/>
                            
                                                    


                                                    </div>
                                 

sending post request from js to php and update mysql

This is y code. I wanted to send data as JSON format from JS file to php. So php can read and update all prices in once. Is it possible?

<?php 
$mysql = mysqli_connect("localhost","root","","db_prices") or die("Error " . mysqli_error($connection));

$data = file_get_contents("php://input"); 
$jsonData = json_decode($data, true);

foreach($jsonData['prices'] as $key => $value) {
if($value) {

//how to use json array to insert data in Database
    mysqli_query($mysql,"UPDATE prices SET price = '".$value."' WHERE price = '". $key ."' LIMIT 1");
    }
}

?>

This is y code. I wanted to send data as JSON format from JS file to PHP. So PHP can read and update all prices in once. Is it possible?

use gujarati fonts shruti with tcpdf

I want to use gujarati fonts in pdf. I used TCPDF V6.4.4. I am using google indic for input gujarati text. My php version is 8.0. I put shruti fonts into fonts folder. I wrote these code.

require_once('TCPDF/tcpdf.php');
$patient1 = "ркЪрк┐рк░рк╛ркЧ";
    $patient2 = "рккрк░ркорк╛рк░";
    $patient3 = "ркорк╛рк░рлБркВ";
    $patient4 = "ркирк╛рко";
    $patient5 = "ркХрк▓рлАркирлАркХ";

    $doctorname="doctorname";
    $filename="filename1.pdf";
    $billreport = "Billreport";
    $pdf_clinicname="pdf clicnicname"; $pdf_address="pdf address";

    $html = '';
    $pdfheader='';
    $html .= '<style>
              body { 
        font-size: 13px;
        color: #000;
        overflow-x: hidden;
        font: inherit;
        }
        .pdfprint{width: 100%; clear: both; float: left; margin: 10px; padding: 10px; color: #000; border: 1px solid #121010; }
        .pdfheader{}
        .leftheader{}
        .red{color: red;}
        .clinicname{font-size: 24px; font-weight: 800;}
        .doctorname{font-size: 20px; font-weight: 800;}
        .doctordegree{font-weight: 600; color: #000; font-size: 12px;}
        .dtagline{}
        .hrtag{clear:both; width: 100%; border: 1px solid #d9d6d6; height: 1px;}
        .namebox{float: left; background-color: #eee;border: 1px solid #e5e6e7;border-radius: 1px; color: inherit; display: block; padding: 6px 6px; margin-right: 10px;}
        .pipesymbol{padding-left: 15px; padding-right: 15px;}
        .rx{font-size: x-large;width: 49%; float: left;}
        .rx2{font-size: x-large; }
        .doclasssection{padding-left: 15px;}
        .patientsection{width: 100%;clear: both; float: left; padding-top: 5px; padding-bottom: 10px;}
        .prescription{width: 49%; float: left;}
        .doclasssection{width: 49%; float: left;}
        .comeafter{width: 100%; float: left; clear: both;}
        .medicinetimetable{float: left; padding-left:50px;}
        </style>';
        $html .= '<body>
                <div id="wrapper">
                    <div id="page-wrapper" class="gray-bg1 dashbard-1">
                        <div id="pdfprint" class="pdfprint chirag1">';

                        $html.='<div class="patientsection" >
                    <div class="patientname">
                        <span class="namebox">'.utf8_encode($patient1).'</span>
                        <span class="namebox">Age : '.utf8_encode($patient2).'</span> <span class="namebox">'.utf8_encode($patient2).'</span>
                        <span class="namebox">ID : '.utf8_encode($patient3).'</span>
                        <span class="namebox">Case No : '.utf8_encode($patient4).'</span>
                        <span class="namebox">Date : '.utf8_encode($patient5).'</span>
                    </div>
                </div> <div class="hrtag"></div>';
         $html.='</div> </div> 
        </div>'; // end wrapper id
        $html.='</body>';

        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // convert TTF font to TCPDF format and store it on the fonts folder
        $fontname = TCPDF_FONTS::addTTFfont('/TCPDF/fonts/shruti.ttf', 'TrueTypeUnicode', '', 96);

        // use the font
        $pdf->SetFont($fontname, '', 14, '', false);

         // set document information
    $pdf->SetCreator(PDF_CREATOR);
    //$pdf->SetAuthor('Nicola Asuni');
    $pdf->SetAuthor($doctorname);
    //$pdf->SetTitle('TCPDF Example 021');
    $pdf->SetTitle($filename);
    //$pdf->SetSubject('TCPDF Tutorial');
    $pdf->SetSubject($billreport);
    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, utf8_encode($pdf_clinicname), utf8_encode($pdf_address));

 // set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    // set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    // set image scale factor
    //$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    // set some language-dependent strings (optional)
    if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
        require_once(dirname(__FILE__).'/lang/eng.php');
        //$pdf->setLanguageArray($l);
    }

    // set font
    $pdf->SetFont('shruti', '', 6);

   $pdf->setFontSubsetting(true);
    // add a page
    $pdf->AddPage();

    // output the HTML content
    $pdf->writeHTML(utf8_encode($html), true, 0, true, 0);

    // reset pointer to the last page
    $pdf->lastPage();

    //Close and output PDF document
    //$pdf->Output('example_021.pdf', 'I');
    $pdf->Output($filename, 'D');

When I run this code, I got this output.
pdf output

Gujrati fonts are not displayed. Please help me to display gujrati fonts into pdf. Thank you in advance.

How to install any version of php with all its extensions?

I am trying to install php 8.0 on a nginx server, I’m following internet tutorials, but I don’t get the expected result. some end up installing apache and deleting my nginx server, others install php but without any extension.

I could put all the codes that I have tried but I don’t even know how to organize them.
I can only say that this blog helped me to install php but in version 7.3.
I try to do it with 8.0 and I get no result, if someone helps me to be able to install the php 8.0 version with all its extensions.

Thanks a lot!

PHP get the basename(__DIR__) of the parent and not the directory of the included file if used inside an include

My structure is as follows

public_html/includes/ contains

includeMe.php

the php inside includeMe.php is

<?php echo basename(__DIR__); ?>

public_html/stuff/ contains

myPage.php

the php inside myPage.php is

<?php include '../includes/includeMe.php'; ?>

The output with this code when I visit stuff/myPage.php is

includes

when I want the output to be

stuff

since this is the parent of where its being included from.

I know this is the correct behaviour for the code i’ve used so my question is, what can I echo within includeMe.php so that the result when called from the include in myPage.php is stuff without the need to move the echo to the myPage.php itself?

Wants to show only the unique custom posts type posts in WordPress front end

I am trying to diplay a custom post type called “positions”, the problem is it has multiple posts with the same title, taxonomies (job_type, city) , custom fields (company). I want to show only one post if title and all the taxonomies and custom fields data are same. And if title and any other taxonomy or custom field matches it should show only one post if there are multiple posts with those details. I was trying to use the following code but it doenst make any changes to the front end. I am using Bricks builder as the page builder. Looking for a wordpress hook or filter to filter posts

`function filter_duplicate_posts( $query ) {
    // Check if the post type is "pay-trackers" and if we're in the main query
    if ( $query->is_main_query() && $query->get( 'post_type' ) == 'positions' ) {
        // Get the post titles of all published posts
        $titles = get_posts( array(
            'post_type' => 'positions',
            'post_status' => 'publish',
            'fields' => 'ids',
            'posts_per_page' => -1
        ) );
 
        // Remove duplicated titles from the array
        $titles = array_unique( $titles );
 
        // Set the post__not_in argument to exclude the duplicated posts
        $query->set( 'post__not_in', $titles );
    }
}
add_action( 'pre_get_posts', 'filter_duplicate_posts' );`

Moodle course images

I’m trying to customise Moodle – 4.O according to my requirements.
I have installed My programs plugin so that we can create a program and add some courses into it.
The thing is I want to display all the courses in the program as cards.
The Course card has to contain Course image, course name, number of learners etc….
I was unable to find where moodle stores these course images in database, so that I can fetch them and display in the card.
Is there any other way to display course image in card?

I checked in every table for that course image, it seems like they are not storing anywhere, but in my courses page,card view, they were displaying the card with images of the course.
I checked the my courses code, but didn’t get how they are rendering the course images.

php mysql query issue [closed]

i need to insert session varibale to insert query near WHERE clause
but when i execute this error is showing

*You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘WHERE *

$sql = "INSERT INTO profiles  WHERE  profile_login_id= $profile_login_id (firstname,middlename,lastname,gender,age,maritial_status,children,how_many_child,location,height  ) 
VALUES ('$firstname','$middlename','$lastname','$gender','$age','$mstatus','$children','$howmanychild','$fcitizenship','$height')";
        
if(mysqli_query($conn, $sql)){
 echo "Records inserted successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}