Search for product titles only – WooCommerce

THE CODE goes to functions.php

// Search titles only 
function __search_by_title_only( $search, $wp_query )
{
    global $wpdb;
    if(empty($search)) {
        return $search; // skip processing - no search term in query
    }
    $q = $wp_query->query_vars;
    $n = !empty($q['exact']) ? '' : '%';
    $search =
    $searchand = '';
    foreach ((array)$q['search_terms'] as $term) {
        $term = esc_sql($wpdb->esc_like($term));
        $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
        $searchand = ' AND ';
    }
    if (!empty($search)) {
        $search = " AND ({$search}) ";
        if (!is_user_logged_in())
            $search .= " AND ($wpdb->posts.post_password = '') ";
    }
    return $search;
}
add_filter('posts_search', '__search_by_title_only', 500, 2);

Add a dynamic fee based on a select field in WooCommerce Checkout

// Add a custom select fields for packing option fee
add_action( 'woocommerce_review_order_after_shipping', 'checkout_shipping_form_packing_addition', 20 );
function checkout_shipping_form_packing_addition( ) {
    $domain = 'woocommerce';

    echo '<tr class="packing-select"><th>' . __('Packing options', $domain) . '</th><td>';

    $chosen   = WC()->session->get('chosen_packing');

    // Add a custom checkbox field
    woocommerce_form_field( 'chosen_packing', array(
        'type'      => 'select',
        'class'     => array( 'form-row-wide packing' ),
        'options'   => array(
            ''    => __("Choose a packing option ...", $domain),
            'bag' => sprintf( __("In a bag (%s)", $domain), strip_tags( wc_price(3.00) ) ),
            'box' => sprintf( __("In a gift box (%s)", $domain), strip_tags( wc_price(9.00) ) ),
        ),
        'required'  => true,
    ), $chosen );

    echo '</td></tr>';
}

// jQuery - Ajax script
add_action( 'wp_footer', 'checkout_shipping_packing_script' );
function checkout_shipping_packing_script() {
    // Only checkout page
    if ( is_checkout() && ! is_wc_endpoint_url() ) :

    WC()->session->__unset('chosen_packing');
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $('form.checkout').on('change', 'select#chosen_packing', function(){
            var p = $(this).val();
            console.log(p);
            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'woo_get_ajax_data',
                    'packing': p,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                    console.log('response: '+result); // just for testing | TO BE REMOVED
                },
                error: function(error){
                    console.log(error); // just for testing | TO BE REMOVED
                }
            });
        });
    });
    </script>
    <?php
    endif;
}

// Php Ajax (Receiving request and saving to WC session)
add_action( 'wp_ajax_woo_get_ajax_data', 'woo_get_ajax_data' );
add_action( 'wp_ajax_nopriv_woo_get_ajax_data', 'woo_get_ajax_data' );
function woo_get_ajax_data() {
    if ( isset($_POST['packing']) ){
        $packing = sanitize_key( $_POST['packing'] );
        WC()->session->set('chosen_packing', $packing );
        echo json_encode( $packing );
    }
    die(); // Alway at the end (to avoid server error 500)
}

// Add a custom dynamic packaging fee
add_action( 'woocommerce_cart_calculate_fees', 'add_packaging_fee', 20, 1 );
function add_packaging_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $domain      = "woocommerce";
    $packing_fee = WC()->session->get( 'chosen_packing' ); // Dynamic packing fee

    if ( $packing_fee === 'bag' ) {
        $label = __("Bag packing fee", $domain);
        $cost  = 3.00;
    } elseif ( $packing_fee === 'box' ) {
        $label = __("Gift box packing fee", $domain);
        $cost  = 9.00;
    }

    if ( isset($cost) )
        $cart->add_fee( $label, $cost );
}

// Field validation, as this packing field is required
add_action('woocommerce_checkout_process', 'packing_field_checkout_process');
function packing_field_checkout_process() {
    // Check if set, if its not set add an error.
    if ( isset($_POST['chosen_packing']) && empty($_POST['chosen_packing']) )
        wc_add_notice( __( "Please choose a packing option...", "woocommerce" ), 'error' );
}

Credit goes to https://stackoverflow.com/questions/57764735/add-a-dynamic-fee-based-on-a-select-field-in-woocommerce-checkout

How to restrict user who have username Barbee or Reynolds and state Ohio woocommerce

Here is code:

add_action( ‘woocommerce_after_checkout_validation’, ‘bbloomer_disallow_pobox_shipping’ );

function bbloomer_disallow_pobox_shipping( $posted ) {
$last_name = ( isset( $posted[‘shipping_last_name’] ) ) ? $posted[‘shipping_last_name’] : $posted[‘billing_last_name’];
$state = ( isset( $posted[‘shipping_state’] ) ) ? $posted[‘shipping_state’] : $posted[‘billing_state’];

$replace = array( ” “, “.”, “,” );

$last_name = strtolower( str_replace( $replace, ”, $last_name ) );
$state = strtolower( str_replace( $replace, ”, $state ) );

if ( ( strstr( $last_name, ‘barbee’ ) || strstr( $last_name, ‘reynolds’ )) && (strstr( $state, ‘oh’ ) || strstr( $state, ‘ohio’ )) ) {
wc_add_notice( ‘Sorry, You are not allowed to order.’, ‘error’ );
}
}

Add this in your function.php in theme.

How to Restrict Access to WordPress Uploads Folder to Logged-in Users only

Here some snippets for Apache web server that need to be added to the .htaccess file which resides in the folder where WordPress is installed.

Option 1: Full Restriction: How to restrict access to all files from residing in the WordPress uploads folder.

# Protect all files within the uploads folder
<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteCond %{HTTP_COOKIE} !.*wordpress_logged_in.*$ [NC]
	RewriteCond %{REQUEST_URI} ^(.*?/?)wp-content/uploads/.* [NC]
	RewriteRule . http://%{HTTP_HOST}%1/wp-login.php?redirect_to=%{REQUEST_URI} [L,QSA]
</IfModule>

Option 2: Partial Restriction: How to restrict access to only to some files (based on their extension) in the uploads folder.

# Protect only some files within the uploads folder
<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteCond %{HTTP_COOKIE} !.*wordpress_logged_in.*$ [NC]
	RewriteCond %{REQUEST_URI} ^(.*?/?)wp-content/uploads/.*\.(?:gif|png|jpe?g|pdf|txt|rtf|html|htm|xlsx?|docx?|mp3|mp4|mov)$ [NC]
	RewriteRule . http://%{HTTP_HOST}%1/wp-login.php?redirect_to=%{REQUEST_URI} [L,QSA]
</IfModule>

HTML Editor Removes Schema (Span) Tags wordpress editor

This short bit of PHP code should be put into your themes functions.php file

function override_mce_options($initArray) {
	$opts = '*[*]';
	$initArray['valid_elements'] = $opts;
	$initArray['extended_valid_elements'] = $opts;
	return $initArray;
}
add_filter('tiny_mce_before_init', 'override_mce_options');
no more messing with your source code when saving or switching views

Credit goes to wpengineer.com

COnvert number to words in south asian numbering system

Here’s a shorter code. with one RegEx and no loops. converts as you wanted, in south asian numbering system. The only limitation is, you can convert maximum of 9 digits, which I think is more than sufficient in most cases..

var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];

function inWords (num) {
    if ((num = num.toString()).length > 9) return 'overflow';
    n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
    if (!n) return; var str = '';
    str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
    str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
    str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
    str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
    str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';
    return str;
}


How To Setup Virtual Hosts Using XAMPP

By default XAMPP sets up all the sites you create to have http://localhost as its top-level domain, and giving your site http://localhost/site as the url unless you install your site in the top-level folder. But what happens when you have multiple sites or you want to test out environments which would require you to have different domains, well I am going to teach you to do just that.

The Steps

  1. You need to have XAMPP installed ( 😐 )
  2. Open up the Xampp control panel and stop Apache (Ensure that you don’t have it running as a service … this is where doing so complicates things)
  3. Navigate to C:/xampp/apache/conf/extra or wherever you installed xampp
  4. Fire up your text editor with administrative privileges and open up httpd-vhosts.conf found in the C:/xampp/apache/conf/extra folder
  5. At the very bottom of the file paste the following
  1. NameVirtualHost *:80
  1. <VirtualHost *:80>
  2. DocumentRoot “C:/xampp/htdocs”
  3. ServerName localhost
  4. </VirtualHost>

With out that line of code you will lose access to your default htdocsdirectory. IE. http://localhost/ will be inaccessible.

  1. Now copy and paste the code below .. below the first code
  1. <VirtualHost *:80>
  2. DocumentRoot “C:/xampp/htdocs/testsite”
  3. ServerName testsite.dev
  4. ServerAlias http://www.testsite.dev
  5. <Directory “c:/xampp/htdocs/testsite”>
  6. Order allow,deny
  7. Allow from all
  8. </Directory>
  9. </VirtualHost>

For Persons using the latest version of Apache (at time of this update 2.4 +) use the code below as the above code is for Apache versions below 2.4

  1. <VirtualHost *:80>
  2. DocumentRoot “C:/xampp/htdocs/testsite”
  3. ServerName testsite.dev
  4. ServerAlias http://www.testsite.dev
  5. <Directory “c:/xampp/htdocs/testsite”>
  6. AllowOverride All
  7. Require all Granted
  8. </Directory>
  9. </VirtualHost>

#Change everywhere you see test site to the location of your site and the domain name you would like to use, the most common ones are .dev, .loc and .local (I believe anything except the traditional .com / .net domains would work fine … but don’t quote me on it)

  1. Now we head over to our Windows Hosts File, to edit the HOSTS. the file will be located at C:/Windows/System32/drivers/etc/hosts, where hosts is the file.
  1. 127.0.0.1 localhost

look for the line above, and enter your site mimicking the layout

  1. 127.0.0.1 localhost
  2. 127.0.0.1 http://www.somesite.dev
  3. 127.0.0.1 http://www.multisite.dev
  4. 127.0.0.1 demo.multisite.dev
  5. 127.0.0.1 http://www.testsite.dev #change this to the domain name you chose earlier

change it to reflect the lines above (if you have problems saving it meant you didn’t have your text editor running in admin mode.

Restart Apache and test to make sure it is working

How to upload multiple files using PHP, jQuery and AJAX

Here is my HTML form :

<form enctype="multipart/form-data" action="upload.php" method="post">
    <input name="file[]" type="file" />
    <button class="add_more">Add More Files</button>
    <input type="button" id="upload" value="Upload File" />
</form>

Finally I have found the solution by using the following code:

$('body').on('click', '#upload', function(e){
        e.preventDefault();
        var formData = new FormData($(this).parents('form')[0]);

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            xhr: function() {
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            success: function (data) {
                alert("Data Uploaded: "+data);
            },
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
        return false;
})

			

Retrieve Facebook Likes Count with PHP

You can get the total number of likes and share count of any web URL with a little bit of PHP and FQL (Facebook Query Language).

function facebook_count($url){
    // Query in FQL
    $fql  = “SELECT share_count, like_count, comment_count “;
    $fql .= ” FROM link_stat WHERE url = ‘$url'”;
    // Facebook Response is in JSON
    $response = file_get_contents($fqlURL);
    return json_decode($response);
}
// facebook share count
echo $fb[0]->share_count;
// facebook like count
echo $fb[0]->like_count;
// facebook comment count
echo $fb[0]->comment_count;
Source : http://ctrlq.org/code/19633-facebook-like-api-php