Monday 27 November 2023

Shipping option update on cart and checkout page using ajax

 


add_action( 'wp_footer', 'refresh_shipping_js' );

function refresh_shipping_js() {

    // Only on checkout

    if( is_checkout() && ! is_wc_endpoint_url() ):

    ?>

    <script type="text/javascript">

    jQuery( function($){

        if (typeof wc_checkout_params === 'undefined') 

            return false;


        var refresh = 'yes';


        $.ajax({

            type: "POST",

            url: wc_checkout_params.ajax_url,

            data: ({

                'action': 'updating_shipping',

                'refresh_shipping': refresh,


            }),

            success: function(response) {

                if( response === '1' ) {

                    $(document.body).trigger('update_checkout');

                    console.log('Success: '+response); // For testing (to be removed)

                } else {

                    console.log('Failled: '+response); // For testing (to be removed)

                }

            },

            error:function(error) {

                console.log('Error: '+error); // For testing (to be removed)

            }

        });

    });

    </script>

    <?php

    endif;

}


// function that gets the Ajax data

add_action( 'wp_ajax_updating_shipping', 'updating_shipping' );

add_action( 'wp_ajax_nopriv_updating_shipping', 'updating_shipping' );

function updating_shipping() {

    if ( isset($_POST['refresh_shipping']) && $_POST['refresh_shipping'] === 'yes' ){

        WC()->session->set('refresh_shipping', '1' );

    } else {

        WC()->session->set('refresh_shipping', '0' );

    }

    echo  WC()->session->get('refresh_shipping');

    die(); // Alway at the end (to avoid server error 500)

}


// Function that refresh session shipping methods data

add_action( 'woocommerce_checkout_update_order_review', 'refresh_shipping_methods', 10, 1 );

function refresh_shipping_methods( $post_data ){

    if ( WC()->session->get('refresh_shipping' ) === '1' ) {

        foreach ( WC()->cart->get_shipping_packages() as $package_key => $package ){

            WC()->session->set( 'shipping_for_package_' . $package_key, false );

        }

        WC()->cart->calculate_shipping();

    }

}

Thursday 14 September 2023

How to skip file when you update the wordpress plugin

function disable_plugin_updates( $value ) {

      if ( isset($value) && is_object($value) ) {

        if ( isset( $value->response['woocommerce/woocommerce.php'] ) ) {

          //unset( $value->response['woocommerce/woocommerce.php'] );

          unset( $value->response['woocommerce/templates/emails/email-order-items.php'] );

        }

      }

      return $value;

    }

    add_filter( 'site_transient_update_plugins', 'disable_plugin_updates' ); 

Sunday 30 July 2023

Backup and Restore MySQL database in PHP

 Script to backup using Php


<?php
define("BACKUP_PATH", "/home/abdul/");

$server_name   = "localhost";
$username      = "root";
$password      = "root";
$database_name = "world_copy";
$date_string   = date("Ymd");

$cmd = "mysqldump --routines -h {$server_name} -u {$username} -p{$password} {$database_name} > " . BACKUP_PATH . "{$date_string}_{$database_name}.sql";

exec($cmd);
?>

Script to restore

<?php

$restore_file  = "/home/abdul/20140306_world_copy.sql";
$server_name   = "localhost";
$username      = "root";
$password      = "root";
$database_name = "test_world_copy";

$cmd = "mysql -h {$server_name} -u {$username} -p{$password} {$database_name} < $restore_file";
exec($cmd);

?>

Wednesday 19 April 2023

Product gallery slider wordpress without plugin on single product page.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flexslider/2.7.0/flexslider.css">

<?php


global $product;


$columns           = apply_filters( 'woocommerce_product_thumbnails_columns', 4 );

$post_thumbnail_id = $product->get_image_id();

$wrapper_classes   = apply_filters(

    'woocommerce_single_product_image_gallery_classes',

    array(

        'woocommerce-product-gallery',

        'woocommerce-product-gallery--' . ( $post_thumbnail_id ? 'with-images' : 'without-images' ),

        'woocommerce-product-gallery--columns-' . absint( $columns ),

        'images',

    )

);


$attachment_ids = $product->get_gallery_image_ids();


if ( $attachment_ids && $product->get_image_id() ) { ?>

        <div class="<?php echo esc_attr( implode( ' ', array_map( 'sanitize_html_class', $wrapper_classes ) ) ); ?>" data-columns="<?php echo esc_attr( $columns ); ?>" style="opacity: 0; transition: opacity .25s ease-in-out;">

            <figure>

                <section class="slider">

                    <div id="slider" class="flexslider">

                        <ul class="slides">

                            <?php 

                            foreach ( $attachment_ids as $attachment_id ) {

                                $image_url = wp_get_attachment_url($attachment_id);

                            ?>

                                <li data-thumb="<?php echo $image_url; ?>">

                                    <img src="<?php echo $image_url; ?>" />

                                </li>

                            <?php } ?>

                        </ul>

                    </div>

                </section>

            </figure>

        </div>

<?php } ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/flexslider/2.7.0/jquery.flexslider.js"></script>

<script type="text/javascript">

    jQuery(window).load(function(){

        jQuery('.flexslider').flexslider({

        animation: "slide",

        controlNav: "none",

        start: function(slider){

            jQuery('body').removeClass('loading');

        }

    });

    });

</script>

Friday 31 March 2023

Reviews Tab always show on single product page.

     $args = array(

        'post_type'      => 'product',

        'posts_per_page' => -1

    );


    $loop = new WP_Query( $args );


    while ( $loop->have_posts() ) : $loop->the_post();

              global $product;

$product->set_reviews_allowed( 'yes' );

$product->save();

    endwhile;


    wp_reset_query();

Wednesday 29 March 2023

Update Custom Cart Count (or any HTML) after AJAX Add to Cart in WooCommerce

 

Template Code

Let’s say you’ve added an element in your header that displays the total cart count, like so:

<div class="header-cart-count"><?php echo WC()->cart->get_cart_contents_count(); ?></div>


add_filter( 'woocommerce_add_to_cart_fragments', 'iconic_cart_count_fragments', 10, 1 );

function iconic_cart_count_fragments( $fragments ) {
    
    $fragments['div.header-cart-count'] = '<div class="header-cart-count">' . WC()->cart->get_cart_contents_count() . '</div>';
    
    return $fragments;
    
}

Saturday 4 February 2023

Create Elementor duplicate pages with different name .

  $csvdata = csv_to_array('../city.csv');

foreach($csvdata as $key=>$csvrow){

if($key==1){

$postidd = get_post(13); 

$frontend = new \Elementor\Frontend();

$pagecontentorg = $frontend->get_builder_content_for_display( 13, $with_css = true );

//apply_filters('the_content', $postidd->post_content); 

$pagecontent = str_replace("problèmes",$csvrow['city'],$pagecontentorg); 

  $post_details = array(

  'post_title'    => 'testing page 5',

  'post_content'  =>$pagecontent,

  'post_status'   => 'publish',

  'post_author'   => 1,

  'post_type' => 'page',

  'page_template'  => 'elementor_header_footer'

   );

   wp_insert_post( $post_details );

/*echo '<pre>';

print_r($csvrow['city']);

echo '</pre>';*/

}

Friday 3 February 2023

Create duplicate pages with different name .

 $postidd = get_post(2457); 

$pagecontent = apply_filters('the_content', $postidd->post_content); 


  /*$post_details = array(

  'post_title'    => 'manjeet page',

  'post_content'  => $pagecontent,

  'post_status'   => 'publish',

  'post_author'   => 1,

  'post_type' => 'page'

   );

   wp_insert_post( $post_details );*/


function csv_to_array($filename='', $delimiter=',')

{

    if(!file_exists($filename) || !is_readable($filename))

        return FALSE;


    $header = NULL;

    $data = array();

    if (($handle = fopen($filename, 'r')) !== FALSE)

    {

        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)

        {

            if(!$header)

                $header = $row;

            else

                $data[] = array_combine($header, $row);

        }

        fclose($handle);

    }

    return $data;

}


$csvdata = csv_to_array('../city.csv');

foreach($csvdata as $csvrow){

echo '<pre>';

print_r($csvrow['city']);

echo '</pre>';

}

Deletes all posts from "products" custom post type.

 /**

* Deletes all posts from "products" custom post type. */ function wpdocs_delete_all_products() { $myproducts = get_pages( array( 'post_type' => 'products') ); foreach ( $myproducts as $myproduct ) { // Delete all products. wp_delete_post( $myproduct->ID, true); // Set to False if you want to send them to Trash. } } add_action( 'init', 'wpdocs_delete_all_products' );

Tuesday 31 January 2023

Save One field data in option table.

 add_action('admin_menu','admin_menu_adding');

add_action('admin_init','admin_reg_settings');


function admin_menu_adding(){

    add_menu_page('Phone Number','Phone Number','administrator','mega-page','settings_page_test');

}


function settings_page_test(){

$phonenumber = get_option('phonenumber');

    ?>

<div class="wrap">

            <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

    <form method="post" action="<?php echo admin_url('options.php'); ?>">

        <?php

        settings_fields('local-settings');

        do_settings_sections('local-settings');

        ?>

<input type="text" name="phonenumber" value="<?php echo $phonenumber; ?>" />

        <?php submit_button(); ?>

    </form>

</div>

    <?php

}


add_action('admin_action_trotbgo','save_value_here');


function save_value_here(){

    update_option();

    exit;

}


function admin_reg_settings(){

    register_setting('local-settings','phonenumber');

}

Friday 20 January 2023

Remove headers already sent error in Wordpress

 for this open wp-config file. remove any space before <?php or after ?>


then open page in notepad++ select encoding ansi first option save. uplaod errors will be removed

How to create Multipurpose Plugin Add Edit Function.

 <?php

ob_start();
/*
Plugin Name:Manjeet Kashyap
Plugin URI: localhost
Description: Declares a plugin that will create a custom post type displaying movie reviews.
Version: 1.0
Author: a1
Author URI:Localhost
License: GPLv2
*/
?>
<?php
function create_menu() {

add_menu_page('cm panel', 'Resigistration', '',  __FILE__, 'settings_page');

add_submenu_page(  __FILE__, 'New_Resigistration', 'New_Resigistration', 'manage_options', 'my-submenu-handle1','settings_page');

add_submenu_page(  __FILE__, 'User_Details', 'User_Details', 'manage_options', 'my-submenu-handle2','section_1');

add_submenu_page(  __FILE__, '', '', 'manage_options', 'my-submenu-handle3','section_2');

}


function settings_page()
{
include('upload1.php');
}

function section_1()
{
include('floor_image.php');
}


function section_2()
{

   $gid=$_GET['id'];

$a="select * from wp_usersinfo where id=$gid";
$res=mysql_query($a);
?>
<form action="" method="post" class="regty" enctype="multipart/form-data">
<?php
while($row=mysql_fetch_array($res)){
?>
<div class="nn1"><span class="lab1">Name</span> <input type="text" name="name_2" value="<?php echo $row['name'];?>"/></div>
<div class="nn1"><span class="lab1">About us</span><textarea cols="59" rows="5" name="about_us_2"><?php echo $row['aboutus'];?></textarea></div>
<div class="nn1"><span class="lab1">Upload Profile image</span><input type="file" name="Photo2" />
<img src="<?php echo bloginfo('template_url').'/images/'.$row['image_name']; ?>" width="125" height="100">
</div>
<div class="nn1"><input type="submit" name="update" value="Update" class="subtn"></div>
<?php
}
?>
</form>

<?php


if(isset($_POST['update'])){
$uploadDir = get_template_directory().'/images/';
$fileName = $_FILES['Photo2']['name'];
$tmpName = $_FILES['Photo2']['tmp_name'];
$fileSize = $_FILES['Photo2']['size'];
$fileType = $_FILES['Photo2']['type'];
$filePath = $uploadDir.$fileName;
$livepath=bloginfo('template_url').'/images/'.$fileName;
$result = move_uploaded_file($tmpName, $filePath);
$a="UPDATE wp_usersinfo SET name='".$_POST['name_2']."'
,image_name='".$fileName."',
image_path='".$filePath."',
aboutus='".$_POST['about_us_2']."'
where id='$gid'";
mysql_query($a) or die(mysql_error());
$admin = admin_url();
header('location:'.$admin.'admin.php?page=my-submenu-handle2');
         }
    }
?>
<?php

/*
function myplugin_activate()
{
global $wpdb;

global $usersinfo_table;

$usersinfo_table = 'wp_usersinfo';

$sql= "CREATE TABLE $table
(id INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
name VARCHAR(250),
image_name VARCHAR( 250 ) NULL ,
image_path VARCHAR( 250 ) NULL ,
aboutus MEDIUMTEXT NULL ,
 )";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);

} */

register_activation_hook( __FILE__, 'myplugin_activate' );
add_action('admin_menu','create_menu');

?>

=============================================================

<style>
.nn1{ float: left;padding: 7px 0; width: 100%;}.nn1 span.lab1 {float: left;width: 14%;}.nn1 input, .nn1 textarea {float: right;margin-right: 2%;width: 80%;}.lab1 input[type="radio"] {float: right; width: auto;}selectorSavingError {
}
</style>
<div class="wrap">
<h2>Registration Form</h2>
</div>
<form action="" method="post" class="regty" enctype="multipart/form-data">
<div class="nn1"><span class="lab1">Name</span> <input type="text" name="name_1" /></div>
<div class="nn1"><span class="lab1">About us</span><textarea cols="59" rows="5" name="about_us_1"></textarea></div>
<div class="nn1"><span class="lab1">Upload Profile image</span><input type="file" name="Photo" /></div>
<div class="nn1"><input type="submit" name="submit" value="submit" class="subtn"></div>
</form>
<?php        
$_POST['Photo'];
$about=$_POST['about_us_1'];
    $name=$_POST['name_1'];

if(isset($_POST['submit']))
{
$imgp=$_POST['Photo'];
$name=$_POST['name_1'];
$url=bloginfo('template_url');
$uploadDir = get_template_directory().'/images/';
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir.$fileName;
$livepath=bloginfo('template_url').'/images/'.$fileName;
$result = move_uploaded_file($tmpName, $filePath);


if (!$result) {
echo "Error uploading file";
//exit;
}

if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}

$table="wp_usersinfo";
 echo $a="insert into wp_usersinfo set name='".$name."' ,
 image_name='".$fileName."',
 image_path='".$filePath."',
 aboutus='".$about."'";
mysql_query($a) or die(mysql_error());
$admin = admin_url();

header('location:'.$admin.'admin.php?page=my-submenu-handle2');
}

================================================================

<?php

include('../../../wp-config.php');
$admin = admin_url();
$uid=$_GET['id'];
$table = 'wp_usersinfo';
$del=mysql_query("DELETE FROM $table WHERE id=$uid");
header('location:'.$admin.'admin.php?page=my-submenu-handle2');
?>

====================================================================

<table border="2">
<tr><th>Id</th>
<th>Name</th>
<th>About us</th>
<th>Image</th>
</tr>
<?php
$admin = admin_url();
$url = plugins_url();
$s="select * from wp_usersinfo";
$result=mysql_query($s);
while($row=mysql_fetch_array($result))
{
echo '<tr><td>'.$row['id'].'</td><td>'.$row['name'].'</td><td>'.$row['aboutus'].'</td><td><img  width="100px" height="100px" src="http://localhost:90/wordpress/wp-content/themes/twentyfourteen/images/'.$row['image_name'].'"/>';
?>
<td>
<a href="<?php echo $admin.'admin.php?page=my-submenu-handle3&id='.$row['id'];?>"><input type="button" name="edit" value="Edit"><a></td>
<td>
<a href="<?php echo $url.'/madhukar/delete.php?id='.$row['id'];?>"><input type="button" name="Delete" value="Delete" ></a>
</td>

</tr>
<?php
}
?>
</table>