Pages

Jan 3, 2023

Get Related Products by Same category

Get Related Products by Same category in single product page


Replace file related.php in /<your-theme>/woocommerce/single-product/



<?php
/**
 * Related Products
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/single-product/related.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see         https://docs.woocommerce.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     3.9.0
 */

if ( ! defined( 'ABSPATH' ) ) {
  exit;
}

global $product, $woocommerce_loop;

if ( empty( $product ) || ! $product->exists() ) {
  return;
}

if ( ! $related = $product->get_related( $posts_per_page ) ) {
  return;
}

// Get ID of current product, to exclude it from the related products query
$current_product_id = $product->get_id();

$cats_array = array(0);

// get categories
$terms = wp_get_post_terms( $product->get_id(), 'product_cat' );

// select only the category which doesn't have any children
foreach ( $terms as $term ) {
  $children = get_term_children( $term->term_id, 'product_cat' );
  if ( !sizeof( $children ) )
  $cats_array[] = $term->term_id;
}

$args = apply_filters( 'woocommerce_related_products_args', array(
  'post_type' => 'product',
  'post__not_in' => array( $current_product_id ),   // exclude current product
  'ignore_sticky_posts' => 1,
  'no_found_rows' => 1,
  'posts_per_page' => $posts_per_page,
  'orderby' => $orderby,
  'tax_query' => array(
    array(
        'taxonomy' => 'product_cat',
        'field' => 'id',
        'terms' => $cats_array
    ),
  )
));

$products                    = new WP_Query( $args );
$woocommerce_loop['name']    = 'related';
$woocommerce_loop['columns'] = apply_filters( 'woocommerce_related_products_columns', $columns );

if ( $products->have_posts() ) : ?>

  <section class="related products">

    <?php
    $heading = apply_filters( 'woocommerce_product_related_products_heading', __( 'Related products', 'woocommerce' ) );

    if ( $heading ) :
    ?>
      <h2><?php echo esc_html( $heading ); ?></h2>
    <?php endif; ?>
    
    <?php woocommerce_product_loop_start(); ?>

      <?php while ( $products->have_posts() ) : $products->the_post(); ?>

        <?php wc_get_template_part( 'content', 'product' ); ?>

      <?php endwhile; // end of the loop. ?>

    <?php woocommerce_product_loop_end(); ?>

  </section>

<?php endif;

wp_reset_postdata();


Dec 7, 2022

How to Connect your Wordpress website to CakePHP Application

WordPress is a popular content management system (CMS) that allows users to easily create and manage websites. CakePHP is an open-source PHP framework that makes it easy to build web applications.

In this blog post, we will look at how to connect WordPress to CakePHP so that you can use the powerful features of both platforms to build powerful and flexible web applications.

First, you will need to install and set up WordPress on your web server. You can find detailed instructions on how to do this in the WordPress documentation.

Next, you will need to install and set up CakePHP on your web server. You can find detailed instructions on how to do this in the CakePHP documentation.

Once you have installed and set up both WordPress and CakePHP, you can connect them by following these steps:

  1. In your WordPress site, go to the plugin directory and search for the "WordPress REST API" plugin. Install and activate this plugin, which will enable the WordPress REST API on your site.

  2. In your CakePHP application, create a new controller and add the following code to it:


// Import the CakePHP HttpClient library
use Cake\Http\Client;

// Define the WordPress site URL
$siteUrl = 'https://www.example.com/';

// Create a new instance of the HttpClient
$http = new Client();

// Make a request to the WordPress site using the HttpClient
$response = $http->get($siteUrl);

// Check the response status code
if ($response->getStatusCode() == 200) {
  // Parse the response body as JSON
  $data = json_decode($response->getBody());

  // Output the data
  debug($data);
}

This code uses the CakePHP HttpClient library to make a request to the WordPress site and parse the response as JSON data. You can then access the data and use it in your CakePHP application.

With this approach, you can easily connect WordPress to CakePHP and use the data and functionality of both platforms to build powerful and flexible web applications.





Oct 7, 2022

Check if cart contains only one product of a perticular category

 

You can search entire cart and checks if it contains only one product of a particular category.

Here suppose your category slug is 'your-category-slug'


Here is a simple function you can place this in your plugin or theme function file


function check_category_alone_in_cart( $category ) {

        

    // check each cart item for our category

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

        

        // if a product is not in our category, bail out since we know the category is not alone

        if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) {

            return false;

        }

    }

        

    // if we're here, all items in the cart are in our category

    return true;

}



function chk_wc_prevent_checkout_for_category() {

    //  If the cart is empty, then let's hit the ejector seat

    

    if (WC()->cart->is_empty()) {

        return;

    }       


    // set the slug of the category for which we disallow checkout

    $category = 'your-category-slug';

    

    // get the product category

    $product_cat = get_term_by( 'slug', $category, 'product_cat' );

    

    // sanity check to prevent fatals if the term doesn't exist

    if ( is_wp_error( $product_cat ) ) {

        return;

    }

    

    // check if this category is the only thing in the cart

    if ( check_category_alone_in_cart( $category ) ) {

        

        // render a notice to explain why checkout is blocked

        wc_add_notice(  'Cart contains the product which has category "your-category-slug" !!! ', 'error' );

return false;

    }  

return true;

}


add_action( 'woocommerce_check_cart_items', 'chk_wc_prevent_checkout_for_category' );


Sep 9, 2021

List of Woocommerce Javascript events

Woocommerce Javascript events


Woocommerce Checkout JS events


$( document.body ).trigger( 'init_checkout' );
$( document.body ).trigger( 'payment_method_selected' );
$( document.body ).trigger( 'update_checkout' );
$( document.body ).trigger( 'updated_checkout' );
$( document.body ).trigger( 'checkout_error' );
$( document.body ).trigger( 'applied_coupon_in_checkout' );
$( document.body ).trigger( 'removed_coupon_in_checkout' );

Woocommerce cart page JS events


$( document.body ).trigger( 'wc_cart_emptied' );
$( document.body ).trigger( 'update_checkout' );
$( document.body ).trigger( 'updated_wc_div' );
$( document.body ).trigger( 'updated_cart_totals' );
$( document.body ).trigger( 'country_to_state_changed' );
$( document.body ).trigger( 'updated_shipping_method' );
$( document.body ).trigger( 'applied_coupon', [ coupon_code ] );
$( document.body ).trigger( 'removed_coupon', [ coupon ] );

Woocommerce Single product page JS events


$( '.wc-tabs-wrapper, .woocommerce-tabs, #rating' ).trigger( 'init' );

Woocommerce Variable product page JS events

$( document.body ).trigger( 'found_variation', [variation] );


Woocommerce Add to cart JS events


$( document.body ).trigger( 'adding_to_cart', [ $thisbutton, data ] );
$( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash, $thisbutton ] );
$( document.body ).trigger( 'removed_from_cart', [ response.fragments, response.cart_hash, $thisbutton ] );
$( document.body ).trigger( 'wc_cart_button_updated', [ $button ] );
$( document.body ).trigger( 'cart_page_refreshed' );
$( document.body ).trigger( 'cart_totals_refreshed' );
$( document.body ).trigger( 'wc_fragments_loaded' );


Woocommerce Add payment method JS events


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

To bind listener to these events, use:

jQuery('<event_target>').on('<event_name>', function(){
    console.log('<event_name> triggered');
});
  
  
Example :

jQuery('body').on('init_checkout', function(){
    console.log('init_checkout triggered');
    // now.do.whatever();
});
  

Mar 2, 2021

2021: best hosting for wordpress ecommerce

2021: best hosting for wordpress ecommerce
# PRODUCT URL PRICE CPU RAM SSD BANDWIDTH DEDICATED IP SSL Email OTHER
1 hostgator https://www.hostgator.in/vps-hosting 3599 INR/month 4 Core CPU 8 GB RAM 120 GB SSD 2 TB Bandwidth 1 Free Dedicated Ips FREE Yes Free Website Migration
2 bluehost https://www.bluehost.in/hosting/vps 3659 INR/month 4 Core CPU 8 GB RAM 120 GB SSD 3 TB Bandwidth 2 IP Addresses FREE Yes(paid) FREE Domain for 1 Year, Microsoft Office Email - Free 30 Days
3 a2hosting[ Managed Hosting] https://www.a2hosting.com/vps-hosting/managed 6252 INR/month 6 Core CPU 8 GB RAM 250 GB SSD 3 TB Bandwidth 2 IP Addresses FREE Yes HTTP3
3 a2hosting[ unManaged Hosting] https://www.a2hosting.com/vps-hosting/unmanaged 6472 INR/month 6 Core CPU 16 GB RAM 250 GB SSD 3 TB Bandwidth 2 IP Addresses FREE Yes HTTP3
4 godaddy https://in.godaddy.com/hosting/ecommerce-hosting 4,499 INR/month 4 Core CPU 8 GB RAM 200 GB SSD unmetered bandwidth 1 Free Dedicated Ips (for first year) FREE (for first year) Yes(paid) LS Cache
5 inmotionhosting https://www.inmotionhosting.com/managed-vps-hosting $1,259.64 for 3 years Unmetered 6GB 150GB 5 TB Bandwidth 4 Dedicated IP's FREE Yes 5 free cPanels + WHM Free and unlimited email accounts Free SSL's

Jan 7, 2020

Auto update sitemap in wordpress

Auto update sitemap in wordpress


/* function to create sitemap.xml file in root directory of site  */        
add_action("publish_post", "eg_create_sitemap");
add_action( "save_post", "eg_create_sitemap" );   
function eg_create_sitemap() {
    $postsForSitemap = get_posts( array(
        'numberposts' => -1,
        'orderby'     => 'modified',
        'post_type'   => array( 'post'),
        'order'       => 'DESC'
    ) );
    $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
    $sitemap .= "\n" . '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";    
    foreach( $postsForSitemap as $post ) {
        setup_postdata( $post );   
        $postdate = explode( " ", $post->post_modified );   
        $sitemap .= "\t" . '<url>' . "\n" .
            "\t\t" . '<loc>' . get_permalink( $post->ID ) . '</loc>' .
            "\n\t\t" . '<lastmod>' . $postdate[0] . '</lastmod>' .
            "\n\t\t" . '<changefreq>monthly</changefreq>' .
            "\n\t" . '</url>' . "\n";
    }     
    $sitemap .= '</urlset>';     
    $fp = fopen( ABSPATH . "sitemap_blog.xml", 'w' );
    fwrite( $fp, $sitemap );
    fclose( $fp );
}

Sep 10, 2019

Append custom class to body element in wordpress



Have you ever wondered how to add custom class to body in any wordpress plugin or page.
Place the below code to update/add new class with any conditions.


add_filter('body_class','append_body_class');
function append_body_class( $classes ) {

    if (is_singular('post')) {
 
    $classes[] =  'news-single';
 
}

 
  return $classes;
}

Fix to increase google page speed (google insight)



If you are stuck in finding a stable solution to score high in google insight pagespeed then there is a simple solution.
Open your function file and add these code :

<?php function motyw_botfix() { ?>

 //Include header scripts and external scripts
//Any kind of scripts that is impossible to break.

<?php }

if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Chrome-Lighthouse') === false) {
add_action('wp_head','motyw_botfix');
}

Aug 29, 2019

Simple method to remotely transfer any files(mdia,zip etc) from one host to another host



Simple method to remotely transfer any files(mdia,zip etc) from one host to another host

<?php
define('BUFSIZ', 4095);
$url = 'http://www.xyz.me/test.zip';
$rfile = fopen($url, 'r');
$lfile = fopen(basename($url), 'w');
while(!feof($rfile))
fwrite($lfile, fread($rfile, BUFSIZ), BUFSIZ);
fclose($rfile);
fclose($lfile);
?>

Step 1: First you need to create a file by any name remote_upload.php your files to be uploaded.
Step 2: Add the above code and replace urls with your actual url to be remotely upload.
Step 3 : Now , run the file remote_upload.php and your requested files will be automatically tranfered in a fraction of second.

Jun 5, 2019

Disable " terms and conditions" toggle and force it to open in a new tab in a checkout page


Disable " terms and conditions"  toggle and force it to open in a new tab in a checkout page
 
WC 3.4.0 +
Use the following remove_action and WC will default back to opening a tab with the terms and conditions page.
add_action( 'wp', 'my_project_wc_change_hooks' );
function my_project_wc_change_hooks() {
  remove_action( 'woocommerce_checkout_terms_and_conditions', 'wc_checkout_privacy_policy_text', 20 );
  remove_action( 'woocommerce_checkout_terms_and_conditions', 'wc_terms_and_conditions_page_content', 30 );
}

Apr 2, 2019

Wordpress Change Password for a logged in user



This is simple method to update Current/Online user password in through wordpress. Remember to
update the required file with extreme precaution as this could affect the user dramatically and might lead to unseen issues, if not handled properly.
$current_user = wp_get_current_user();
   $user_id = $current_user->ID;  //Current User Id
   $current_pswd =  $_POST['$current_pswd']; //CURRENT PASSWORD

  $new_pswd =   $_POST['$new_pswd'];//NEW PASSWORD
  $confirm_pswd =    $_POST['$confirm_pswd'];//CONFIRM PASSWORD

if(  $confirm_pswd ==  $new_pswd )   {

     if( wp_check_password( $current_pswd, $current_user->data->user_pass, $user_id)){
      $user_data = array(
      'ID' => $user_id,
      'user_pass' => $new_pswd
      );
      wp_update_user($user_data);
      wp_logout();

     $validation = 'SUCCESS';
 
     }else{

     $validation = 'ERROR FAILED';
    }
   }else{
    $validation = 'TOTAL ERROR';

}

echo $validation ;

    

Oct 6, 2016

Prevent DDoS attack in wordpress



By default, this feature is enabled in all Wordpress installs, and isn't quite easy to turn off. Add the following API filter to Wordpress:

add_filter( ‘xmlrpc_methods’, function( $methods ) {

   unset( $methods['pingback.ping'] );   return $methods;} );

Removing xmlrpc.php is not recommended as it will breack a number of other features that will use the API.

Aug 21, 2016

Add a '' container inside after every 3 loops




Add a '<div></div>'  container inside after every 3 loops
As an example

<div>
    title
    title
    title
</div>
<div>
    title
    title
    title
</div>
<div>
    title
    title
    title
</div>
.
.
.
$dummyarray is in format of
$dummyarray = array(


[0] => 'title',

[1] => 'title',

[2] => 'title',

[3] => 'title',

.
.
)

foreach (array_chunk($dummyarray, 3, true) as $array)
{
    echo '<div>';
    foreach($array as $foo)
    {
         echo $foo->title;
    }
    echo '</div>';
}

Jun 20, 2016

Create CRON In wordpress with custom interval


Create CRON In wordpress with custom interval


// add custom interval
function cron_add_minute( $schedules ) {
// Adds once every minute to the existing schedules.
    $schedules['everyminute'] = array(
   'interval' => 60,
   'display' => __( 'Once Every Minute' )
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'cron_add_minute' );



add_action('recheck_event', 'recheck_verification');

function schedule_event() {
if ( !wp_next_scheduled( 'recheck_event' ) ) {
wp_schedule_event( current_time( 'timestamp' ), 'everyminute', 'recheck_event');
}
}
add_action('wp', 'schedule_event');

function recheck_verification() {

 //You Custom Function

}

Jun 18, 2016

Prevent admin notification email for new registered users or user password changes

This is a simple method to prevent any mails to admin which normaly takes place on new user registration or user changes there password. Put this function on your Function.php file any where.

// prevent admin notification email for new registered users or user password changes



function conditional_mail_stop() {

    global $phpmailer;

    $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
    $subject = array(
        sprintf(__('[%s] New User Registration'), $blogname),
        sprintf(__('[%s] Password Lost/Changed'), $blogname)
    );

    if ( in_array( $phpmailer->Subject, $subject ) )
        // empty $phpmailer class -> email cannot be send
        $phpmailer = new PHPMailer( true );

}

add_action( 'phpmailer_init', 'conditional_mail_stop' );

May 27, 2016

FUNCTION TO ADD CUSTOM STYLE SHEET IN A PLUGIN

FUNCTION TO ADD CUSTOM STYLE SHEET IN A PLUGIN


function msg_script_init() {

 wp_enqueue_style("msgcs", plugins_url('user-messages/css/msgcss.css'), false, "0.0", "all");

}
add_action('admin_init', 'msg_script_init');

May 3, 2016

How to add custom Google Translation with custom flag

Adding google translation to any page in html/php using Google Translation


Create span element for flags :-

  <span class="flags">
                   <span class="flag_click eng" data-val = 'en'><flag-img></span>
                   <span class="flag_click spn" data-val = 'es'><flag-img></span>
 

 

 

 


Add following Script below this :-

 

 

 

<script>
               
 function changeLang(someth) {
    var nLang = someth;//someth.value,
        evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    jQuery('.goog-te-combo').val(nLang)[0].dispatchEvent(evt);
}

   jQuery('document').ready(function () {
                 jQuery('.flag_click').click(function () {
                    
                 var va =  jQuery(this).attr('data-val');
                  changeLang(va);
                   });
     });
    </script>
   
<div class="translator_div" style="display:none;"> 

                            <div id="google_translate_element"></div><script type="text/javascript">
                            function googleTranslateElementInit() {
                            new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'en,es', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element');
                            }
                            </script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
   </div>

 

 

Apr 22, 2016

Using Jquery hiw To get values In A Text Box On “Keyup” Event


How to Get Values In A Text Box On “Keyup” Event using jquery


<input type=”text” id=”keywords” value=””/>
<script>
jQuery(“#keywords”).keyup(function(e)
{
var searchbox = jQuery(this).val();
alert(searchbox);
});
</script>