Posts

WooCommerce: Redirect to Checkout after Add to Cart

There are instances where a person may want to redirect the user to checkout after adding items to cart ie. if they use Woocommerce booking appointment and can only book one time. The below code snippet allows for changing the behaviour of the Add to Cart button. Code add_filter( 'woocommerce_add_to_cart_redirect', 'themename_add_to_cart_redirect' ); function themename_add_to_cart_redirect( $url ) { return get_permalink( get_option( 'woocommerce_checkout_page_id' ) ); } Where to add this Code snippet? Usually, the code is added in functions.php of your child theme. As shown below: /path/to/wordpress/wp-content/themes/mytheme-child/functions.php I don't have access to this functions.php As an alternative, you can also install and use a plugin called Code Snippets  from the admin. Log into your WordPress admin Click Plugins Click Add New Search for Code Snippets Click Install Now under "Code Snippets" Activ...

Woocommerce: Hide Coupon Field on the CART

The following code snippet shows how to hide the coupon field on Cart page in Woocommerce. Code add_filter( 'woocommerce_coupons_enabled', 'hp_hide_coupon_field_on_cart' ); function hp_hide_coupon_field_on_cart( $enabled ) { if ( is_cart() ) { $enabled = false; } return $enabled; } Where to add this Code snippet? Usually, the code is added in functions.php of your child theme. As shown below: /path/to/wordpress/wp-content/themes/mytheme-child/functions.php I don't have access to this functions.php As an alternative, you can also install and use a plugin called Code Snippets from the admin. Log into your WordPress admin Click Plugins Click Add New Search for Code Snippets Click Install Now under "Code Snippets" Activate the plugin Under Code Snippets, click Add New Paste and publish the code above

Javascript: Redirect to Another Page

Redirect to Another Page With Javascript // window.location window.location.replace('http://www.example.com') window.location.assign('http://www.example.com') window.location.href = 'http://www.example.com' document.location.href = '/path' // window.history window.history.back() window.history.go(-1) // window.navigate; ONLY for old versions of Internet Explorer window.navigate('top.jsp') Redirect to Another Page With JQuery $(location).attr('href','http://www.example.com') $(window).attr('location','http://www.example.com') $(location).prop('href', 'http://www.example.com')

jQuery: Check Element Visibility

For a single element, it is very easy to check if an element is hidden or visible: $(element).is(":visible"); $(element).is(":hidden"); To match all elements, use the ff: $('element:hidden'); $('element:visible') You can also check the CSS display property: if ( $(selector).css('display') == 'none' ) { // is hidden } else { // is visible }

jQuery: Open Bootstrap Modal on Form Submit

This simple snippet shows how to open Bootstrap Modal on form submission using jQuery. Bootstrap has provided functions you can use to manually manipulate the modal. $('#myModal').modal('toggle'); $('#myModal').modal('show'); $('#myModal').modal('hide'); Here is an example form <form action="/process" onsubmit="openModal()" id="myForm"> Call the function manually function openModal(){ $('#myModal').modal('show'); return false; } Using the jQuery  Event Listener $('#myForm').on('submit', function(e){ $('#myModal').modal('show'); }); See Demo in CodePen See the Pen Bootstrap Modal on Form Submit by Hana Piers ( @hanapiers ) on CodePen .

jQuery: Disable Closing of Modal in Bootstrap

Bootstrap's Modal default behavior is that it closes when you click outside the window. To disable it, Bootstrap, provided simple solution: With jQuery You can initialize the modal settings backdrop property to "static" $('#myModal').modal({ backdrop: 'static', keyboard: false }); You may noticed that we also set keyboard property to false. This is to disable the use of ESC button to close the modal. Though I would recommend this only as alternative. It is still preferred to use HTML and Bootstrap has just made it possible. Use backdrop data attribute According to Boostrap, if you set data-backdrop to "static", this will disable the modal from closing. <a data-controls-modal="#yourId" data-backdrop="static" data-keyboard="false" href="#">

Javascript: Capitalize First Word of String (EASY)

In Javascript, you can make the first word uppercase by using the technique below. function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } var str = "lorem ipsum dolor"; capitalize(str); // output: "Lorem ipsum dolor" To explain what's going on, the function takes the first letter of given string and convert it to uppercase then append to the rest of the given string. We can modify the String.prototype if you don't mind a little setback on the performance. String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); } Now we can call the function in object oriented way: var str = "lorem ipsum dolor"; console.log(str.capitalize()); // output: "Lorem ipsum dolor"

Javascript: Get Query String (Easy)

Image
This tutorial assumes that you already know what a query string is. If you are looking for a way to get the query string values and assign to a variable, then check the following block of codes. Do note that this is only pure Javascript. No need for plugins or libraries. var queryString = {}; var params = location.search.substr(1).split('&'); params.forEach(function( param ){     [name, value] = param.split('=');     queryString[name] = decodeURIComponent((value).replace(/\+/g, '%20')); }); // check the output console.log(queryString); In the above code, we use location.search which is the way to get the query string. The result of location.search . would be a string type like this: ?key1=value1&key2=value2 To get the desired result we want, we first remove the '?' mark with .substr(1) , then split the string with delimiter '&' The resulting array is then looped through using .forEach() . For each array item we then spli...

jQuery: Select an element by name

Image
Although the title says jQuery  in it, I will also provide Javascript solution for this snippet. Live Demo at CodePen Suppose we have the following checkbox input: <input type="checkbox" name="colors" value="red" /> Red <input type="checkbox" name="colors" value="green" /> Green <input type="checkbox" name="colors" value="blue" /> Blue in jQuery: var colors = $('[name="colors"]'); // non-element specific var colors = $('input[name="colors"]'); // specific to "input" elements only in JavaScript: // returns array of elements with name="colors" var colors = document.getElementsByName('colors'); var colors = document.querySelectorAll('[name="colors"]'); // returns first element with name="colors" var colors = document.getElementsByName('colors')[0]; var colors = documen...

Pass Values from PHP to Javascript

Image
There are many ways to pass PHP variables to Javascript but I will only cover 3 most common: 1. Echo the data. 2. Use a hidden field or element. 3. Use a data attribute 1. Echo the data. The first one which is the simplest can be done as follows: var data = <?php echo $data;  ?>; But the above code can cause an issue depending on the data type and it's value, so we use json_encode to convert the data. In PHP: $name = "John O'Reily";     // a string with single quote $age = 14;                           // an integer number $address = array(                // an array     'street' => '123 Street',     'city' => 'XYZ City' ); In Javascript: var name = <?php echo json_encode($name);  ?>; var age = parseInt(<?php echo json_encode($age);  ?>); var address = <?php echo json_encode($address);  ?...

Javascript: Creating a dynamic Copyright footer

Image
Updating your website's copyright year on annual basis can be annoying, to make your copyright year dynamically change, simply use the new Date.getFullYear(); code as shown in the example below. Live Demo  at CodePen the HTML: &copy; 1997 - <span id="currentYear"></span> // desired ouput: © 1997 - 2017 on pure Javascript: document.getElementById('currentYear').innerHTML = new Date().getFullYear(); or if you use jQuery [ CodePen demo ]: $('#currentYear').html(new Date().getFullYear());

Redis: The Basics

Image
What is Redis ? - Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker - Remote Dictionary Server Installation For Mac OS X: 1. Install XCode Developer Tools 2. Download the stable release on Redis official site: http://redis.io/download 3. Run the ff. command: wget http://download.redis.io/releases/redis-3.2.0.tar.gz tar xzf redis-3.2.0.tar.gz cd redis-3.2.0 # install and run globally (/usr/local/bin) make install redis-server # install and run locally make cd src && ./redis-server # install on another location make install /opt/local/bin For Ubuntu: 1. Run the ff. command: sudo apt-get install redis-server # run redis-server Data Types List: - collection of string elements, sorted according to the order of insertion. ex. 8, 9, 1, 2, 3 - implemented using a linked list, not using an array - insertion of new elements to head or tail is at constant time regardless of the length of the list ...

PHPUnit: Basics of Unit Testing

Image
What is Unit Testing ? Unit Testing is a software testing method by which individual units of code are tested to determine if they are fit to use. Benefits of Unit Testing - find problems early - facilitates changes - simplifies integration - documentation - design interface What is PHPUnit? - xUnit-style library by Sebastian Bergmann - Installable via Composer, PEAR and Phar - well integrated and well documented reference: http://phpunit.de/manual/current/en/index.html Installation (globally via Phar) wget https://phar.phpunit.de/phpunit.phar chmod +x phpunit.phar mv phpunit.phar /usr/bin/phpunit source: http://phpunit.de/manual/current/en/installation.html Installation (as vendor via Composer) Create a composer.json file in the root directory then add the ff.: { "require-dev" : { "phpunit/phpunit" : "4.8.0" }, "autoload" : { "psr-4" : { "Project\\" : "app...

Install Symfony on Vagrant Environment

Image
Vagrant is a tool for building and managing virtual machine environments. Assuming you have already installed and  vagrant up your virtual environment. Execute the following instructions on your terminal console. Download symfony installer sudo curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony sudo chmod a+x /usr/local/bin/symfony Create project directory symfony new my_project Then, you can: * Change your current directory to /vagrant/my_project * Configure your application in app/config/parameters.yml file. * Run your application: 1. Execute the php bin/console server:run command. 2. Browse to the http://localhost:8000 URL. * Read the documentation at http://symfony.com/doc Running #1, should produce result similar to this: php bin/console server:run [OK] Server running on http://127.0.0.1:8000 // Quit the server with CONTROL-C. If you have private network map set in Vagrantfile then do not use server:run as it only listens to http...

Python: Install ansible with pip

Note that ansible can only be run on a machine with Python 2.6 or 2.7 Install ansible package using pip module: sudo pip install ansible Install required packages: sudo pip install paramiko PyYAML Jinja2 httplib2 six To install the latest development version: sudo pip install git+git://github.com/ansible/ansible.git@devel

Python: Creating Virtual Environments and Managing Packages

Creating the Virtual Environment Using virtualenv virtualenv [env_name] source [env_name]/bin/activate Using pyvenv (includes pip in the default packages) pyvenv [env_name] source [env_name]/bin/activate Managing Packages Install the latest version of package: pip install [package_name] Alternatively, you can use python -m to install a package using pip module: python -m [module_name] install [package_name] Install a specific version of a package pip install [package_name]==[version] If you would like to install the flask package with a minimum version, this is how to execute it: pip install flask>=0.10.1 Install packages just for the current user: pip install --user [package_name] Upgrade a package to the latest version: pip install --upgrade [package_name] Remove package(s) from the virtual environment: pip uninstall [package1] [package2] ... [package] Display information about a particular package: pip show [package] Display all the packages installed in...

Vagrant: Installing Vagrant

Download VirtualBox and Vagrant Create a directory for your virtual environment mkdir vagrant_env1 cd vagrant_env1 Install your preferred box (Ubuntu 12.04 LTS 64-bit for this example): vagrant init hashicorp/precise64 or vagrant init vagrant box add hashicorp/precise64 You may check this HashiCorp's Atlas box catalog for more type of boxes. By the way, a "box" is a base image of an operating system. This enables you to quickly clone a virtual machine rather than starting from scratch, which would be a slow and tedious process. Installing may take some time, but after that, you can re-use this box when you want to create another virtual environment. Now run vagrant up: vagrant up To enter the virtual machine, simply SSH: vagrant ssh

Python: Install pip on Mac OS X

Download get-pip.py Run the following command: sudo python get-pip.py Upgrading pip: pip install -U pip

Vim: Using Abbreviations

VIM abbreviations can save typing and/or improve typing accuracy. By using :ab or :abbreviate , you can define abbreviations in VIM editor or the .vimrc file. i.e. This command will automatically replace "cia" with "central intelligence agency" :ab cia central intelligence agency or :abbreviate cia central intelligence agency i.e. You can also shorten a line of code :ab ubb #! /usr/bin/bash The above code will replace ubb with #! /usr/bin/bash The following command will remove a specific abbreviation :una ubb or :unabbreviate ubb This command will remove all abbreviations defined :abc or :abclear

Bash: Caret Substitution

Sample command: echo "dev" && echo "my dev" Replace "dev" with "prod": ^dev^prod Previous command will now be this: echo "prod" && echo "my dev" To replace all occurences of "dev": ^dev^prod^:& Previous command will now be this: echo "prod" && echo "my prod"