WooCommerce Snippet – Search product by SKU

// Search product by SKU (functions.php)
add_filter( ‘posts_search’, ‘bbloomer_product_search_by_sku’, 9999, 2 );
function bbloomer_product_search_by_sku( $search, $wp_query ) {
global $wpdb;
if ( ! is_search() || ! isset( $wp_query->query_vars[‘s’] ) || ( ! is_array( $wp_query->query_vars[‘post_type’] ) && $wp_query->query_vars[‘post_type’] !== “product” ) || ( is_array( $wp_query->query_vars[‘post_type’] ) && ! in_array( “product”, $wp_query->query_vars[‘post_type’] ) ) ) return $search;
$product_id = wc_get_product_id_by_sku( $wp_query->query_vars[‘s’] );
if ( ! $product_id ) return $search;
$product = wc_get_product( $product_id );
if ( $product->is_type( ‘variation’ ) ) {
$product_id = $product->get_parent_id();
}
$search = str_replace( ‘AND (((‘, “AND (({$wpdb->posts}.ID IN (” . $product_id . “)) OR ((“, $search );
return $search;
}

Resource : https://www.businessbloomer.com/woocommerce-search-products-by-sku/

WordPress – WooCommerce Product Display Quantity Sold

// functions.php

/* Dev – Display product sold count at shop page */
add_action( ‘woocommerce_after_shop_loop_item’, ‘cxc_get_product_sold_count_at_shop’, 9 );
function cxc_get_product_sold_count_at_shop() {
global $product;
$sales = $product->get_total_sales();
// $stock = $product->get_stock_quantity();
if ( $sales ) { echo ‘<span>’ . $sales . ‘ sold</span>’; }
}

/* Dev – Display product sold count at product page */
add_action( ‘woocommerce_single_product_summary’, ‘cxc_get_product_sold_count_at_product’, 30 );
function cxc_get_product_sold_count_at_product() {
global $product;
$units_sold = $product->get_total_sales();
// $units_stock = $product->get_stock_quantity();
if ( $units_sold ) { echo ‘<span>’ . $units_sold . ‘ sold</span>’; }
}

Reference : https://codexcoach.com/display-total-product-sold-quantity-to-woocommerce-product-page/

CSS – Snow Animation

<div class=”snowflake”>❅</div>
<div class=”snowflake”>❅</div>
<div class=”snowflake”>❆</div>
<div class=”snowflake”>❄</div>
<div class=”snowflake”>❅</div>
<div class=”snowflake”>❆</div>
<div class=”snowflake”>❄</div>
<div class=”snowflake”>❅</div>
<div class=”snowflake”>❆</div>
<div class=”snowflake”>❄</div>

<style>
.snowflake {
color: #fff;
font-size: 1em;
font-family: Arial;
text-shadow: 0 0 1px #000;
z-index: -1;
}

@-webkit-keyframes snowflakes-fall{0%{top:-10%}100%{top:100%}}@-webkit-keyframes snowflakes-shake{0%{-webkit-transform:translateX(0px);transform:translateX(0px)}50%{-webkit-transform:translateX(80px);transform:translateX(80px)}100%{-webkit-transform:translateX(0px);transform:translateX(0px)}}@keyframes snowflakes-fall{0%{top:-10%}100%{top:100%}}@keyframes snowflakes-shake{0%{transform:translateX(0px)}50%{transform:translateX(80px)}100%{transform:translateX(0px)}}.snowflake{position:fixed;top:-10%;z-index:9999;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:default;-webkit-animation-name:snowflakes-fall,snowflakes-shake;-webkit-animation-duration:10s,3s;-webkit-animation-timing-function:linear,ease-in-out;-webkit-animation-iteration-count:infinite,infinite;-webkit-animation-play-state:running,running;animation-name:snowflakes-fall,snowflakes-shake;animation-duration:10s,3s;animation-timing-function:linear,ease-in-out;animation-iteration-count:infinite,infinite;animation-play-state:running,running}.snowflake:nth-of-type(0){left:1%;-webkit-animation-delay:0s,0s;animation-delay:0s,0s}.snowflake:nth-of-type(1){left:10%;-webkit-animation-delay:1s,1s;animation-delay:1s,1s}.snowflake:nth-of-type(2){left:20%;-webkit-animation-delay:6s,.5s;animation-delay:6s,.5s}.snowflake:nth-of-type(3){left:30%;-webkit-animation-delay:4s,2s;animation-delay:4s,2s}.snowflake:nth-of-type(4){left:40%;-webkit-animation-delay:2s,2s;animation-delay:2s,2s}.snowflake:nth-of-type(5){left:50%;-webkit-animation-delay:8s,3s;animation-delay:8s,3s}.snowflake:nth-of-type(6){left:60%;-webkit-animation-delay:6s,2s;animation-delay:6s,2s}.snowflake:nth-of-type(7){left:70%;-webkit-animation-delay:2.5s,1s;animation-delay:2.5s,1s}.snowflake:nth-of-type(8){left:80%;-webkit-animation-delay:1s,0s;animation-delay:1s,0s}.snowflake:nth-of-type(9){left:90%;-webkit-animation-delay:3s,1.5s;animation-delay:3s,1.5s}

</style>

Resource : https://codepen.io/codeconvey/pen/xRzQay

WordPress woocommerce – New Arrival tag

// functions.php
add_action( ‘woocommerce_before_shop_loop_item_title’, ‘bbloomer_new_badge_shop_page’, 3 );
function bbloomer_new_badge_shop_page() {
global $product;
$newness_days = 7;
$created = strtotime( $product->get_date_created() );
if ( ( time() – ( 60 * 60 * 24 * $newness_days ) ) < $created ) {
echo ” . esc_html__( ‘New Arrival’, ” ) . ”;
}
}

Reference : https://www.businessbloomer.com/woocommerce-new-badge-recent-products/

Sticky Bar

<video width=”1000″ height=”500″ id=”vid” controls autoplay muted loop playsinline>
<source src=”…/video.mp4″ type=”video/mp4″>
Your browser does not support the video tag.
</video>

<style>
video#vid {
position: fixed;
z-index: 9;
bottom:0;
left: 50%;
transform: translate(-50%, 30%);
max-width: 100%;
width: 500px;
}
</style>

<script>document.getElementById(“vid”).controls = false;</script>

References :
https://www.w3schools.com/tags/tag_video.asp
https://pqina.nl/blog/fix-html-video-autoplay-not-working/
https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

htaccess – http to https

  RewriteEngine On

  RewriteBase /  
  RewriteCond %{HTTP_HOST} ^domain.com [NC]
  RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301,NC]
  RewriteCond %{SERVER_PORT} 80
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

css – background images

<style>
div {
/* background-image: url(topleft.png), url(bottomright.png); */
/* background-position: right bottom, left top; */
/* background-repeat: no-repeat, no-repeat; */
background: url(topleft.png) right bottom no-repeat, url(bottomright.png) left top no-repeat;
}
</style>

References :
https://www.w3schools.com/css/css3_backgrounds.asp
https://www.w3schools.com/css/tryit.asp?filename=trycss3_background_multiple
https://www.w3schools.com/css/tryit.asp?filename=trycss3_background_multiple2

js – Scroll SlideUp effect

<style>
.js-slidein {
opacity: 0;
transform: translateY(100px);
-webkit-transition: all 300ms ease-in-out;
transition: all 300ms ease-in-out;
}
.js-slidein-visible {
opacity: 1 !important;
transform: translateY(0) !important;
}
</style>

<script>
$(document).ready(function () {
var breakpoint = 840;
// If the screen is smaller then 840px wide remove all classes.
if ($(window).width() < breakpoint) {
$(‘.js-slidein’).removeClass(‘js-slidein’);
}

// Check which of the elements with this class is visible on the page
$(‘.js-slidein’).each(function (i) {
var bottomObject = $(this).offset().top;
var bottomWindow = $(window).scrollTop() + $(window).height();
if (bottomWindow > bottomObject) {
$(this).removeClass(‘js-slidein’);
}
});

// Trigger the slide-in effect on scroll
$(window).scroll(function () {
$(‘.js-slidein’).each(function (i) {
var bottomObject = $(this).offset().top + $(this).outerHeight() / 3;
var bottomWindow = $(window).scrollTop() + $(window).height();
if (bottomWindow > bottomObject) {
$(this).addClass(‘js-slidein-visible’);
}
});
});
});
</script>

<div class=”js-slidein”></div>

Resources :
https://www.jqueryscript.net/animation/slide-in-scroll.html
https://www.jqueryscript.net/demo/slide-in-scroll/

js – select month and days dropdown

<select name=”day” id=”day”>
<option value=”” disabled selected>DD</option>
<option value=’1′>1</option>
<option value=’2′>2</option>
<option value=’3′>3</option>
<option value=’4′>4</option>
<option value=’5′>5</option>
<option value=’6′>6</option>
<option value=’7′>7</option>
<option value=’8′>8</option>
<option value=’9′>9</option>
<option value=’10’>10</option>
<option value=’11’>11</option>
<option value=’12’>12</option>
<option value=’13’>13</option>
<option value=’14’>14</option>
<option value=’15’>15</option>
<option value=’16’>16</option>
<option value=’17’>17</option>
<option value=’18’>18</option>
<option value=’19’>19</option>
<option value=’20’>20</option>
<option value=’21’>21</option>
<option value=’22’>22</option>
<option value=’23’>23</option>
<option value=’24’>24</option>
<option value=’25’>25</option>
<option value=’26’>26</option>
<option value=’27’>27</option>
<option value=’28’>28</option>
<option value=’29’>29</option>
<option value=’30’>30</option>
<option value=’31’>31</option>
</select>

<select name=”month” id=”month”>
<option value=”” disabled selected>MM</option>
<option value=’1′>Janaury</option>
<option value=’2′>February</option>
<option value=’3′>March</option>
<option value=’4′>April</option>
<option value=’5′>May</option>
<option value=’6′>June</option>
<option value=’7′>July</option>
<option value=’8′>August</option>
<option value=’9′>September</option>
<option value=’10’>October</option>
<option value=’11’>November</option>
<option value=’12’>December</option>
</select>

<script>
var getDaysInMonth = function(month,year) {
return new Date(year, month, 0).getDate();
};

$(‘#month’).change(function() {
//alert(getDaysInMonth(this.value, 2020));
var selectDay = $(“#day”);
selectDay.empty();

var days = getDaysInMonth(this.value, 2020);
for (var d = 1; d <= days; d++){
var dayElem = document.createElement(“option”);
dayElem.value = d;
dayElem.textContent = d;
selectDay.append(dayElem);
}
});
</script>

References :
https://www.w3resource.com/javascript-exercises/javascript-date-exercise-3.php
https://stackoverflow.com/questions/51659414/populate-dropdown-list-with-current-day-month-and-year

CSS – Columns and tiles

#gallery {
display: grid;
grid-template-columns: repeat( auto-fit, minmax(calc(100%/3), 1fr) );
/* Fr is a fractional unit and 1fr is for 1 part of the available space. */
}
.column1 {
grid-column: 1 / 3;
grid-row: 1;
}
.column2 {
grid-column: 3 ;
grid-row: 1;
}
.column3 {
grid-column: 1 ;
grid-row: 2 ;
}
.column4 {
grid-column: 2;
grid-row: 2;
}
.column5 {
grid-column: 3;
grid-row: 2;
}
.column6 {
grid-column: 1 ;
grid-row: 3;
}
.column7 {
grid-column: 1;
grid-row: 4;
}
.column8 {
grid-column: 2 / 4;
grid-row: 3 / 5;
}

References :
https://stackoverflow.com/questions/47601564/equal-width-columns-in-css-grid
https://www.one-eight-one.com/gallery/flower-shop

php – replace half string by character

<?php
$string = “abcdefghijklmnopqrstuvwxyz”;

//separate half
$long = strlen($string);
$half = $long/2;

$head = substr($string, 0, $half);
$tail = substr($string, $half);

//replace by x
$tail = str_repeat(“x”,strlen($tail));

echo $head.$tail;
?>

CSS – gallery tiles

div.container {
display: grid;
grid-gap: 5px;
}
div:nth-child(1) {
grid-column: 1 / 3;
grid-row: 1;
}
div:nth-child(2) {
grid-column: 3 ;
grid-row: 1;
}
div:nth-child(3) {
grid-column: 1 ;
grid-row: 2 ;
}
div:nth-child(4) {
grid-column: 2;
grid-row: 2;
}
div:nth-child(5) {
grid-column: 3;
grid-row: 2;
}
div:nth-child(6) {
grid-column: 1 ;
grid-row: 3;
}
div:nth-child(7) {
grid-column: 1;
grid-row: 4;
}
div:nth-child(8) {
grid-column: 2 / 4;
grid-row: 3 / 5;
}

Reference : https://gridbyexample.com/examples/example5/

Datepicker js (plugin) – (minDate) arrival departure

$(‘#arrival’).datepicker({minDate: 0, dateFormat: ‘mm/dd/yy’, onSelect: function(dateStr) {
var date = $(this).datepicker(‘getDate’);
if (date) {
date.setDate(date.getDate() + 1);
}
$(‘#departure’).datepicker(‘option’, ‘minDate’, date || 1);
$(‘#departure’).val($.datepicker.formatDate(‘mm/dd/yy’, date || 1));
}});
$(‘#departure’).datepicker({minDate: 1, dateFormat: ‘mm/dd/yy’, onSelect: function(dateStr) {
var date = $(this).datepicker(‘getDate’);
if (date) {
date.setDate(date.getDate() – 1);
}
//$(‘#arrival’).datepicker(‘option’, ‘maxDate’, date);
$(‘#arrival’).val($.datepicker.formatDate(‘mm/dd/yy’, date));
}});

Reference : https://forum.jquery.com/topic/datepicker-add-1-day-to-selected-day

php – strtotime (change date format, issue 1970)

<?php
function formatDate($date)
{
if (strpos($date,’/’) !== false) :
$date = str_replace(‘/’, ‘-‘, $date);
$date = date(‘Y-m-d h:i:s’, strtotime($date));
else :
$date = date(‘d-m-Y h:i:s’, strtotime($date));
$date = str_replace(‘-‘, ‘/’, $date);
endif;
return $date;
}
?>

<?php
echo date(“d F Y”, strtotime(“19-04-23”)); //23 April 2019
echo date(“d F Y”, strtotime(“23-04-19”)); //19 April 2023
echo date(“d F Y”, strtotime(“23-04-2019”)); //23 April 2019
echo date(“d F Y”, strtotime(“23/04/2019”)); //01 January 1970
echo formatDate(“23/04/2019”); //2019-04-23 12:00:00
echo date(“d F Y”, strtotime(formatDate(“23/04/2019”))); //23 April 2019
?>

Reference : https://php.net/manual/en/function.strtotime.php

html css – Radio Rating

<style>
#rating { direction: rtl; text-align: left; }
#rating input:checked ~ label, .#rating input:hover ~ label { color: gold; }
#rating input { opacity: 0; position: absolute; }
</style>

<di v id=”rating”>
<input type=”radio” name=”rating” value=”5″ id=”star5″/><label for=”star5″>★</label>
<input type=”radio” name=”rating” value=”4″ id=”star4″/><label for=”star4″>★</label>
<input type=”radio” name=”rating” value=”3″ id=”star3″/><label for=”star3″>★</label>
<input type=”radio” name=”rating” value=”2″ id=”star2″/><label for=”star2″>★</label>
<input type=”radio” name=”rating” value=”1″ id=”star1″/><label for=”star1″>★</label>
</div>

Reference : https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-css-selector

js – upload file size limit

<input type=”file” id=”file” name=”file”>
<s cript>
document.getElementById(“file”).onchange = function() {
if(this.files[0].size > 1000000){
alert(“Attachment can not greater than 1 MB.”);
this.value = “”;
}};
</script>

<input type=”file” id=”files” name=”files[]” multiple>
<s cript>
document.getElementById(“files”).onchange = function() {
for (var i = 0; i < this.files.length; i++) {
alert(this.files[i].size);
//alert(this.files[i].name);
//alert(this.files[i].type);
}};
</script>

Resource : https://jsfiddle.net/hibbard_eu/7bjfr/

php – reCaptcha*

<s cript src=”https://www.google.com/recaptcha/api.js ” async defer></script>
<form method=”POST” action=””>
<d iv class=”g-recaptcha” data-sitekey=”your-data-sitekey”></div>
<input type=”submit” value=”Submit” />
</form>

<?php
if($_POST){
$secretKey = “your-secret-key”;
$ip = $_SERVER[‘REMOTE_ADDR’];
$response=file_get_contents(“https://www.google.com/recaptcha/api/siteverify?secret= “.$secretKey.”&response=”.$_POST[‘g-recaptcha-response’].”&remoteip=”.$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys[“success”]) !== 1) {
echo ‘<s cript>alert(“Please check the the captcha form.”);</script>’;
} else {
echo ‘<s cript>alert(‘Thank you for your email’);</script>’;
}
}
?>

Resources :
https://codeforgeek.com/2014/12/google-recaptcha-tutorial/
https://github.com/codeforgeek/Google-recaptcha-php
https://github.com/codeforgeek/Google-recaptcha-php/blob/master/form.php
https://www.google.com/recaptcha/admin#list

php – form mail attachment*

<form enctype=”multipart/form-data” method=”POST” action=””>
Name<input type=”text” name=”name” /><br/>
Email<input type=”email” name=”email” /><br/>
Phone<input type=”tel” name=”phone” /><br/>
Message<textarea name=”message”></textarea><br/>
Attachment<input type=”file” name=”my_files[]” multiple/><br/>
<input type=”submit” value=”Submit” />
</form>

<?php
if($_POST){

$subject = “Subject”;
$recepient = “recipient@email.com”;

$attachments = $_FILES[‘my_files’];
$file_count = count($attachments[‘name’]); //count total files attached
$boundary = md5(“sanwebe.com”);

//construct a message body to be sent to recipient
$message_body =”Name : “.$_POST[‘name’].”\r\n”;
$message_body.=”Phone : “.$_POST[‘phone’].”\r\n”;
$message_body.=”Email : “.$_POST[’email’].”\r\n”;
$message_body.=”Message : “.$_POST[‘message’].”\r\n”;

if($file_count > 0){ //if attachment exists
//header
$headers = “MIME-Version: 1.0\r\n”;
$headers .= “From:”.$_POST[’email’].”\r\n”;
$headers .= “Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n”;

//message text
$body = “–$boundary\r\n”;
$body .= “Content-Type: text/plain; charset=ISO-8859-1\r\n”;
$body .= “Content-Transfer-Encoding: base64\r\n\r\n”;
$body .= chunk_split(base64_encode($message_body));

//attachments
for ($x = 0; $x < $file_count; $x++){
if(!empty($attachments[‘name’][$x])){

if($attachments[‘error’][$x]>0) //exit script and output error if we encounter any
{
$mymsg = array(
1=>”The uploaded file exceeds the upload_max_filesize directive in php.ini”,
2=>”The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form”,
3=>”The uploaded file was only partially uploaded”,
4=>”No file was uploaded”,
6=>”Missing a temporary folder” );
print $mymsg[$attachments[‘error’][$x]];
exit;
}

//get file info
$file_name = $attachments[‘name’][$x];
$file_size = $attachments[‘size’][$x];
$file_type = $attachments[‘type’][$x];

//read file
$handle = fopen($attachments[‘tmp_name’][$x], “r”);
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

$body .= “–$boundary\r\n”;
$body .=”Content-Type: $file_type; name=”.$file_name.”\r\n”;
$body .=”Content-Disposition: attachment; filename=”.$file_name.”\r\n”;
$body .=”Content-Transfer-Encoding: base64\r\n”;
$body .=”X-Attachment-Id: “.rand(1000,99999).”\r\n\r\n”;
$body .= $encoded_content;
}
}

}else{ //send plain email otherwise
$headers = “From:”.$_POST[’email’].”\r\n”.
“X-Mailer: PHP/” . phpversion();
$body = $message_body;
}

$sentMail = mail($recepient, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
echo “<scr ipt>alert(‘Success.’);</script>”; //exit;
}else{
echo “<scr ipt>alert(‘Failure.’);</script>”; //exit;
}
}
?>

Reference : https://www.sanwebe.com/2011/01/send-php-mail-with-attachment

js – pagination

<ul id=”pages”></ul>

<s cript>
function page(p){
$total = $(‘.item’).length;
$items = 9; //items per page
$page = p; //page number
$pages = Math.ceil($total/$items); //total page
$max = $page*$items; //upper boundary
$min = $max-$items; //lower boundary

document.getElementById(“pages”).innerHTML = “”;
for($p=1; $p<=$pages; $p++){
if($p==$page){
document.getElementById(“pages”).innerHTML = document.getElementById(“pages”).innerHTML + “<li class=’active’ onclick=’page(“+$p+”)’>” + $p + “</li>”;
}else{
document.getElementById(“pages”).innerHTML = document.getElementById(“pages”).innerHTML + “<li onclick=’page(“+$p+”)’>” + $p+ “</li>”;
}
}

$(‘.item’).hide();
$i=1;
$(‘.item’).each(function() {
if($i>$min && $i<=$max) {
$(this).show();
} $i++;
});
}
</script>

PHP – Mail Form

<form action=”” method=”post” id=”contact-form” name=”contact_form” onSubmit=”return validation();”>
<p><input type=”text” placeholder=”Name *” name=”name” id=”name”></p>
<p><input type=”text” placeholder=”Email *” name=”email” id=”email”></p>
<p><input type=”text” placeholder=”Telephone *” name=”phone” id=”phone”></p>
<p><textarea placeholder=”Message *” name=”message” id=”message” rows=”5″></textarea></p>
<p><input type=”submit” value=”SEND” id=”submit” name=”enquire_submit”></p>
</form>

<?php
if(isset($_POST[‘enquire_submit’])){
$to = ‘stephanie_lee@webstergy.com’;
$emailBCC = ‘stephanie_lee@webstergy.com’;
$subject=”Contact Form”;
$header = ‘From: =?UTF-8?B?’.base64_encode($_POST[‘name’]).’?= <‘.$_POST[’email’].’>’.”\r\n”;
if($emailBCC != ”){ $header .= ‘BCC: ‘.$emailBCC.”\r\n”; }
$header .= ‘Reply-To: ‘ . $_POST[’email’] . “\r\n”;
$header .= “Content-type: text/html; charset=UTF-8”;

$message =”Name : “.$_POST[‘name’].”<br/>”;
$message.=”Email : “.$_POST[’email’].”<br/>”;
$message.=”Phone : “.$_POST[‘phone’].”<br/>”;
$message.=”Message : “.$_POST[‘message’].”<br/>”;
$sentmail = mail($to,$subject,$message,$header);

if($sentmail){
$input = $_POST[‘name’]; //get input text
$success = “Hi “.$_POST[‘name’].”, your info has been success submitted! We will get back to you soon.”;
echo ‘<s cript>alert(“‘.$success.'”)</script>’;
}
else {
$failed = “Sorry, please reinsert valid information.”;
echo ‘<s cript>alert(“‘.$failed.'”)</script>’;
}
}
?>

<s cript>
function checkEmail(str){
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (filter.test(str)){ return true; }else{ return false; }
}

function validation() {
if (document.getElementById(“name”).value == “”){
alert(“Please enter your name”);
return false;
}else if(document.getElementById(“email”).value == “” || !checkEmail(document.getElementById(“email”).value)){
alert(“Please enter valid email”);
return false;
}else if(document.getElementById(“phone”).value == “” || (!/^[+]?\d+[- ]?\d+[- ]?\d+$/.test(document.getElementById(“phone”).value))){
alert(“Please enter valid phone number”);
return false;
}else{ return true; }
}
</script>

Reference : http://yemayaspa.com.sg/

Google – reCAPTCHA (complete)

<s cript src=”https://www.google.com/recaptcha/api.js&#8221; async defer></script>
<d iv class=”g-recaptcha” data-sitekey=”6LfZR1kUAAAAAHNGQ8onEoDjIF7_2m6ZAVvtV1J-“></div>

<?php
// Construct the Google verification API request link.
function googleRecaptcha($g_recaptcha_response){
$params = array();
$params[‘secret’] = ‘your-secret-key’; // Secret key

if(isset($g_recaptcha_response)){
$params[‘response’] = urlencode($g_recaptcha_response);
}
$params[‘remoteip’] = $_SERVER[‘REMOTE_ADDR’];

$params_string = h ttp_build_query($params);
$requestURL = ‘https://www.google.com/recaptcha/api/siteverify?&#8217; . $params_string;

// Get cURL resource
$curl = curl_init();

// Set some options
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $requestURL,
));

// Send the request
$response = curl_exec($curl);

// Close request to clear up some resources
curl_close($curl);

$response = @json_decode($response, true);
return $response;
}

$responseData = $this->googleRecaptcha($_POST[‘g-recaptcha-response’]);
//print_r($responseData); exit; //testing

if($responseData[success]==1){ } else{ } //your-function-here
?>

Resources :
http://punkguitar77.com/index.php?option=com_contact&view=contact&id=1&Itemid=61&lang=en
– punkguitar77.com/components/com_contact/controller.php

js – Back to Top

<a onclick=”$(‘html, body’).animate({ scrollTop: 0 }, 800);” style=”position:fixed; bottom:0;” id=”top”><i class=”fas fa-angle-up”></i></a>

<s cript>
window.onscroll = function() {topFunction()};
function topFunction() {
var x = $(“div”).position(); //anchor
if (document.body.scrollTop > x.top || document.documentElement.scrollTop > x.top) {
$(‘#top’).css(‘display’,’block’);
} else {
$(‘#top’).css(‘display’,’none’);
}
}
</script>

References :
https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_css_position
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onscroll2

grecaptcha – js get response

The response from the user’s captcha challenge can be got three ways. It can be as,
– g-recaptcha-response – a POST parameter in the submitted form (php)
grecaptcha.getResponse() – will provide the response after the user completes the captcha. (js)
– A string argument to the callback function specified in the config object passed to the render method.

<s cript>
function() { // js – grecaptcha.getResponse(widget_id) – will provide the response after the user completes the captcha.
//alert(grecaptcha.getResponse());
var response = window.grecaptcha.getResponse(); //alert(response);
if(response.length == 0) { } else { }
return; }
</script>
<s cript src=’https://www.google.com/recaptcha/api.js‘></script >
<d iv class=”g-recaptcha” data-sitekey=”—————————————-“></div>

Reference :
http://www.codedodle.com/2014/12/google-new-recaptcha-using-javascript.html
https://stackoverflow.com/questions/30278139/how-to-get-recaptcha-client-verification-parameter-g-recaptcha-response-after-us
https://developers.google.com/recaptcha/docs/display
https://stackoverflow.com/questions/27902539/how-can-i-validate-google-recaptcha-v2-using-javascript-jquery
https://developers.google.com/recaptcha/docs/display#js_api
https://developers.google.com/recaptcha/docs/verify

plugin datepicker – get year, month, day

var checkindate = $(‘#checkin’).datepicker(‘getDate’);
var checkoutdate = $(‘#checkout’).datepicker(‘getDate’);

var checkinYear = checkindate.getFullYear();
var checkinMonth = checkindate.getMonth()+1;
var checkinDay = checkindate.getDate();

var checkoutYear = checkoutdate.getFullYear();
var checkoutMonth = checkoutdate.getMonth()+1;
var checkoutDay = checkoutdate.getDate();

SVG – animation circle / loading / spinner

<svg width=”200px” height=”200px” xmlns=”http://www.w3.org/2000/svg ” viewBox=”0 0 100 100″>
<circle
cx=”50″
cy=”50″
fill=”none”
stroke=”#b2b594″
stroke-width=”5″
r=”40″
stroke-dasharray=”164.93361431346415 56.97787143782138″
transform=”rotate(168 50 50)”
stroke-linecap=”round”>
<animateTransform
attributeName=”transform”
type=”rotate”
calcMode=”linear”
values=”0 50 50;360 50 50″
keyTimes=”0;1″
dur=”1s”
begin=”0s”
repeatCount=”indefinite”>
</animateTransform>
</circle>
</svg>

References :
https://codepen.io/aurer/pen/jEGbA
https://loading.io
https://tech.scrunch.com/blog/creating-an-animated-svg-spinner/

js – set/get cookies

<s cript>
function setCookie(name, value) //*
{
var today = new Date();
var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // 30 days
document.cookie=name + “=” + escape(value) + “; path=/; expires=” + expiry.toGMTString();
}
function getCookie(name) //*
{
var re = new RegExp(name + “=([^;]+)”);
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}

function saveCookie() {
setCookie(“cname”, $(“#name”).val());
}
function loadCookie() {
if (getCookie(“cname”)!=null) { $(“#name”).val(getCookie(“cname”)); }
}
</script>

Resources :
http://www.the-art-of-web.com/javascript/setcookie/
http://www.the-art-of-web.com/javascript/getcookie/

js, php – checkbox array

<?php
$str = “0,1,2,3”;
$str = explode(‘,’, $str); //into array
//if(in_array(‘0’, $str)) { echo “!”; }
?>

<input type=”hidden” id=”result”>
<input type=”checkbox” value=”1″ class=”box” id=”a” <?php if(in_array(1, $str)){echo “checked”;} ?> ><label for=”a”>1</label>
<input type=”checkbox” value=”2″ class=”box” id=”b” <?php if(in_array(2, $str)){echo “checked”;} ?> ><label for=”b”>2</label>
<input type=”checkbox” value=”3″ class=”box” id=”c” <?php if(in_array(3, $str)){echo “checked”;} ?> ><label for=”c”>3</label>

<s cript>
$(‘.box’).change(function() {
var arr = []; //new array
$(“.box:checked”).each(function(){
arr.push($(this).val());
});
//alert(arr);
$(‘#result’).val(arr);
});
</script>

References :
https://stackoverflow.com/questions/590018/getting-all-selected-checkboxes-in-an-array
https://www.w3schools.com/php/func_string_explode.asp

js – pagination plugin

<s cript src=”https://cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js”></script >

<d iv id=”listing”>
<input type=”text” class=”search” />
<d iv class=”list”>
<p class=”item”>Guybrush Threepwood</p>
<p class=”item”>Elaine Marley</p>
<p class=”item”>LeChuck</p>
<p class=”item”>Stan</p>
<p class=”item”>Voodoo Lady</p>
<p class=”item”>Herman Toothrot</p>
<p class=”item”>Meathook</p>
<p class=”item”>Carla</p>
<p class=”item”>Otis</p>
<p class=”item”>Rapp Scallion</p>
<p class=”item”>Rum Rogers Sr.</p>
<p class=”item”>Men of Low Moral Fiber</p>
<p class=”item”>Murray</p>
<p class=”item”>Cannibals</p>
</div>
<ul class=”pagination”></ul>
</div>

<s cript>
var monkeyList = new List(‘listing’, {
valueNames: [‘item’],
page: 3,
pagination: true
});
</script>

<style> .pagination li { display:inline-block; } </style>

Resource : http://listjs.com/examples/pagination/

js – dropdown sync

<select id=”field1″ name=””>
<option value=”value1″>text1</option>
<option value=”value2″>text2</option>
<option value=”value3″>text3</option>
</select>
<input type=”text” id=”field2″ name=”” />

<s cript>
$(‘#field1’).change(function() {
//$(‘#field2’).val($(this).val());
$(‘#field2’).val($(‘#field1 option:selected’).text());
//document.getElementsByName(‘field’)[0].value = this.value;
});
</script>

Reference : https://stackoverflow.com/questions/3170648/how-to-get-javascript-select-boxs-selected-text

CSS3 – tiles

@media only screen and (min-width: 400px) {
.masonry {
-moz-column-count: 2;
-webkit-column-count: 2;
column-count: 2;
}
}

@media only screen and (min-width: 700px) {
.masonry {
-moz-column-count: 3;
-webkit-column-count: 3;
column-count: 3;
}
}

@media only screen and (min-width: 900px) {
.masonry {
-moz-column-count: 4;
-webkit-column-count: 4;
column-count: 4;
}
}

@media only screen and (min-width: 1100px) {
.masonry {
-moz-column-count: 5;
-webkit-column-count: 5;
column-count: 5;
}
}

Resources :
http://w3bits.com/css-masonry/
http://w3bits.com/labs/css-masonry/

php – detect mobile

<?php
$useragent=$_SERVER[‘HTTP_USER_AGENT’];
if(preg_match(‘/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i’,$useragent)||preg_match(‘/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i’,substr($useragent,0,4))) {
}
?>

WolfCMS – Drag Reorder

<a href=”#” id=”reorder-toggle”><?php echo __(‘reorder’); ?></a>
<img class=”handle” src=”<?php echo URI_PUBLIC;?>wolf/admin/images/drag.gif” alt=”<?php echo __(‘Drag and Drop’); ?>” align=”middle” />

<s cript type=”text/javascript”>
jQuery.fn.sortableSetup = function sortableSetup() {
this.sortable({
placeholder:’placeholder’,
handle: ‘.handle’,
cursor:’crosshair’,
stop: function(event, ui) {
var order = $(ui.item.parent()).sortable(‘serialize’, {key: ‘layouts[]’});
//dev
$(‘.list‘).each(function(i){
//$(this).addClass(” + ++i);
$(this).val(” + ++i);
});
}
})
//.disableSelection();
return this;
};

$(document).ready(function() {
$(‘ul#layouts‘).sortableSetup();
$(‘#reorder-toggle’).toggle(
function(){
$(‘ul#layouts‘).sortable(‘option’, ‘disabled’, false);
$(‘.handle’).show();
$(‘#reorder-toggle’).text(‘<?php echo __(‘disable reorder’);?>’);
},
function() {
$(‘ul#layouts‘).sortable(‘option’, ‘disabled’, true);
$(‘.handle’).hide();
$(‘#reorder-toggle’).text(‘<?php echo __(‘reorder’);?>’);
}
)
});
</script>

WordPress – ContactForm7 dropdown select placeholder

/wp-content/themes/[theme]/functions.php

function my_wpcf7_form_elements($html) {
function ov3rfly_replace_include_blank($name, $text, &$html) {
$matches = false;
preg_match(‘/<select name=”‘ . $name . ‘”[^>]*>(.*)<\/select>/iU’, $html, $matches);
if ($matches) {
$select = str_replace(‘<option value=””>—</option>’, ‘<option value=””>’ . $text . ‘</option>’, $matches[0]);
$html = preg_replace(‘/<select name=”‘ . $name . ‘”[^>]*>(.*)<\/select>/iU’, $select, $html);
}
}
ov3rfly_replace_include_blank(‘menu-name‘, ‘Please Select‘, $html);
return $html;
}
add_filter(‘wpcf7_form_elements’, ‘my_wpcf7_form_elements’);

Source : http://www.programmingscripts.com/how-to-add-placeholder-text-in-contact-form-7-dropdown/

PHP 5.5 – preg_replace to preg_replace_callback

/* PHP Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead */

// Old version
$uppercaseValue = preg_replace(
‘/(^|_)([a-z])/e‘,
strtoupper(“\\1”)’,
$string
);

// New version
$uppercaseValue = preg_replace_callback(
‘/(^|_)([a-z])/’,
function($matches) { return strtoupper($matches[1]); },
$string
);

Resource : https://blog.liplex.de/replace-preg_replace-with-preg_replace_callback-for-php-5-5/

PHP – Extract Youtube ID from URL

<?php
function get_youtube_id_from_url($url)
{
if (stristr($url,’youtu.be/’))
{preg_match(‘/(https:|http:|)(\/\/www\.|\/\/|)(.*?)\/(.{11})/i’, $url, $final_ID); return $final_ID[4]; }
else
{@preg_match(‘/(https:|http:|):(\/\/www\.|\/\/|)(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})/i’, $url, $IDD); return $IDD[5]; }
}

$youtube_url=’http://www.youtube.com/watch?var1=blabla#v=GvJehZx3eQ1$var2=bla’;
echo get_youtube_id_from_url($youtube_url); // outputs: GvJehZx3eQ1
?>

Resource : https://stackoverflow.com/questions/3392993/php-regex-to-get-youtube-video-id

Fancybox – Numbering

// v1.3.4
$(document).ready(function(){
$(“.fancybox”).fancybox({
‘titlePosition’: ‘over’,
‘titleFormat’: function(title, currentArray, currentIndex, currentOpts) {
return ‘<span id=”fancybox-title-over”>Image ‘ + (currentIndex + 1) + ‘ of ‘ + currentArray.length + ‘ ‘ + title + ‘</span>’;
}
});
});

// v2.x
$(document).ready(function() {
$(“.fancybox”).fancybox({
helpers : {
title : { type : ‘inside’ }
},
afterLoad : function() {
this.title = (this.title ? ” + this.title + ‘<br />’ : ”) + ‘Image ‘ + (this.index + 1) + ‘ of ‘ + this.group.length;
}
});
});

// v2.0.6+
$(document).ready(function(){
$(“.fancybox”).fancybox({
helpers : {
title : { type : ‘over’ }
},
beforeShow : function() {
this.title = (this.title ? ” + this.title + ” : ”) + ‘Image ‘ + (this.index + 1) + ‘ of ‘ + this.group.length;
}
});
});

// v3.1.20
$( ‘[data-fancybox]’ ).fancybox({
caption : function( instance, item ) {
var caption = $(this).data(‘caption’) || ”;
return ‘(<span data-fancybox-index></span>/<span data-fancybox-count></span>)’ + ( caption.length ? ‘ ‘ + caption : ” );
}
});

Reference : https://stackoverflow.com/questions/11603753/fancybox-displaying-the-number-of-total-images-in-the-group

HTML5 – Canvas Coordinates

<canvas id=”myCanvas” width=”700″ height=”300″ style=”border:solid 1px;”></canvas>

<s cript>
function writeMessage(canvas, message, x, y) {
var context = canvas.getContext(‘2d’);
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = ’18pt’;
context.fillStyle = ‘red’;
context.fillText(message, x, y);
}

function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX – rect.left,
y: evt.clientY – rect.top
};
}

var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);

canvas.addEventListener(‘click’, function(evt) {
var mousePos = getMousePos(canvas, evt);
var message = mousePos.x + ‘,’ + mousePos.y;
writeMessage(canvas, message, mousePos.x, mousePos.y);
}, false);

</script>

Source : http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/

Sign in with LinkedIn

1. Initialize the SDK (https://www.linkedin.com/developer/apps)
<head>
<s cript type=”text/javascript” src=”//platform.linkedin.com/in.js”>
api_key: YOUR_API_KEY_HERE
authorize: true
onLoad: onLinkedInLoad
</script>
</head>

2. Create the “Sign In with LinkedIn” button
<body>
<s cript type=”in/Login”></script>
</body>

3. Handle async authentication & retrieve basic member data
<s cript type=”text/javascript”>

// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, “auth”, getProfileData);
}

// Handle the successful return from the API call
function onSuccess(data) {
console.log(data); // Ctrl+Shirt+J

//
console.log(data.firstName);
console.log(data.lastName);
}

// Handle an error response from the API call
function onError(error) {
console.log(error);
}

// Use the API call wrapper to request the member’s basic profile data
function getProfileData() {
IN.API.Raw(“/people/~”).result(onSuccess).error(onError);
}

</script>

4. Create a “Sign out” button
<button onclick=”IN.User.logout();>Logout</button>

Resource : https://developer.linkedin.com/docs/signin-with-linkedin

CSS – Checkbox

<input type=”checkbox” id=”box1″>
<label for=”box1″>Sustainable typewriter cronut</label>

<input type=”checkbox” id=”box2″>
<label for=”box2″>Gentrify pickled kale chips </label>

<input type=”checkbox” id=”box3″>
<label for=”box3″>Gastropub butcher</label>

<style>
input[type=”checkbox”] { display: none; }

input[type=”checkbox”] + label {
position: relative;
padding-left: 25px;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}

input[type=”checkbox”] + label:before {
content: ”;
width: 20px;
height: 20px;
border: 1px solid red;
position: absolute;
left: 0;
top: 0;
-webkit-transition: all .12s, border-color .08s;
transition: all .12s, border-color .08s;
}

input[type=”checkbox”]:checked + label:before {
width: 10px;
top: -5px;
left: 5px;
border-top-color: transparent;
border-left-color: transparent;
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}
</style>

Reference : https://codepen.io/valerypatorius/pen/oXGMGL

js – Anchor Smooth Scrolling

<s cript>
$(document).ready(function(){
// Add smooth scrolling to all links
$(“a”).on(‘click’, function(event) {

// Make sure this.hash has a value before overriding default behavior
if (this.hash !== “”) {
// Prevent default anchor click behavior
event.preventDefault();

// Store hash
var hash = this.hash;

// Using jQuery’s animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$(‘html, body’).animate({
scrollTop: $(hash).offset().top
}, 800, function(){

// Add hash (#) to URL when done scrolling (default click behavior)
// window.location.hash = hash;
});
} // End if
});
});
</script>

Reference : https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll

Opencart – Warning: Your IP is not allowed to access this API!

<modification>
<file name=”admin/controller/common/login.php”>
<operation>
<search position=”after”><![CDATA[ $this->session->data[‘token’] = token(32); ]]></search>
<add><![CDATA[
$this->db->query(“INSERT INTO oc_api_ip (api_id, ip) SELECT * FROM (SELECT ‘1’, ‘”.$_SERVER[‘REMOTE_ADDR’] .”‘) AS tmp WHERE NOT EXISTS (SELECT ip FROM oc_api_ip WHERE ip = ‘”.$_SERVER[‘REMOTE_ADDR’].”‘) LIMIT 1;”);
]]>
</add>
</operation>
</file>
</modification>

Reference : https://github.com/opencart/opencart/issues/3554

Google – Invisible reCAPTCHA

<html>
<head>
<title>Invisible reCAPTCHA</title>
<s cript src=”https://www.google.com/recaptcha/api.js” async defer></script>
<s cript>
function onSubmit(token) {document.getElementById(“demo-form”).submit();}
<!– function onSubmit(token) {document.demo_form.submit();} –>
</script>
</head>
<body>
<form id=’demo-form’ name=”demo_form” action=”?” method=”POST”>
<input type=”submit” class=”g-recaptcha” data-sitekey=”your_site_key” data-callback=’onSubmit’>
</form>
</body>
</html>

Source : https://developers.google.com/recaptcha/docs/invisible

PHPMailer – Attachment input file

<form action=”mail.php” method=”post” enctype=”multipart/form-data”>
<input type=”email” name=”email” required/>
<input type=”file” name=”upload” required/>
<input type=”submit” name=”submit” value=”Send”/>
</form>

<?php require(‘phpmailer/class.phpmailer.php’); //https://github.com/PHPMailer/PHPMailer
if(isset($_POST[‘submit’])){
$mail->AddAddress($_POST[’email’]);

if(is_array($_FILES)) {
$mail->AddAttachment($_FILES[‘upload’][‘tmp_name’],$_FILES[‘upload’][‘name’]);
}

$mail->Send();
} ?>

References :
http://stackoverflow.com/questions/12301358/send-attachments-with-php-mail
https://github.com/PHPMailer/PHPMailer
http://www.codesynthesis.co.uk/tutorials/attach-a-file-to-an-email-in-php-using-phpmailer
http://phppot.com/jquery/jquery-contact-form-with-attachment-using-php/
http://stackoverflow.com/questions/5628011/how-to-upload-a-file-to-my-server-using-html

Safari Select CSS

select {
padding: 1em 3em;
background-color: white;

-webkit-appearance: none;
-moz-appearance: none;
appearance: none;

-moz-border-radius: 0px;
-webkit-border-radius: 0px;
border-radius: 0px;

background-image: linear-gradient(45deg, transparent 50%, gray 50%), linear-gradient(135deg, gray 50%, transparent 50%);
background-position: calc(100% – 20px) calc(1em + 10px), calc(100% – 15px) calc(1em + 10px), calc(100% – 2.5em) 0.5em;
background-size: 5px 5px, 5px 5px, 1px 1.5em;
background-repeat: no-repeat;
}

js – toggle (suggested for responsive menu)

<b utton id=”navbar-toggle”>Menu</button>
<d iv class=”navbar-collapse” style=”display:none;”>Content</div>

<s cript>
$(document).ready(function(){
$(“#navbar-toggle”).toggle(
function(){
//$(‘.navbar-collapse’).addClass(‘active’);
$(‘.navbar-collapse’).css(“display”, “block”);
},
function(){
//$(‘.navbar-collapse’).removeClass(‘active’);
$(‘.navbar-collapse’).css(“display”, “none”);
}
);
})
</script>

References :
http://stackoverflow.com/questions/13275831/make-an-onclick-event-do-something-different-every-other-click
http://jsfiddle.net/rajnish/j6gWa/

Slick Slider – Slides Syncing

<link rel=”stylesheet” type=”text/css” href=”http://kenwheeler.github.io/slick/slick/slick.css “/>
<link rel=”stylesheet” type=”text/css” href=”http://kenwheeler.github.io/slick/slick/slick-theme.css “/>
<s cript type=”text/javascript” src=”http://code.jquery.com/jquery-1.11.0.min.js “></script>
<s cript type=”text/javascript” src=”http://code.jquery.com/jquery-migrate-1.2.1.min.js “></script>
<s cript type=”text/javascript” src=”http://kenwheeler.github.io/slick/slick/slick.js “></script>

<di v class=”col-lg-6 slider-for”>
<di v>1</div>
<di v>2</div>
<di v>3</div>
<di v>4</div>
<di v>5</div>
</div>
<di v class=”col-lg-6 slider-nav”>
<di v>1</div>
<di v>2</div>
<di v>3</div>
<di v>4</div>
<di v>5</div>
</div>

<s cript>
$(window).load(function() {
$(‘.slider-for’).slick({
arrows: false,
fade: true,
asNavFor: ‘.slider-nav’
});
$(‘.slider-nav’).slick({
asNavFor: ‘.slider-for’
});
});
</script>

Resource : http://kenwheeler.github.io/slick/

JavaScript – FancyBox YouTube (jQuery plugin)

<!– Add fancyBox main JS and CSS files –>
<s cript type=”text/javascript” src=”http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.1.7″></script&gt;
<link rel=”stylesheet” type=”text/css” href=”http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.1.7 ” media=”screen” />

<a class=”video” title=”The Falltape” href=”http://www.youtube.com/v/ZeStnz5c2GI?fs=1&amp;autoplay=1″><img src=”images/1.jpg” alt=”” /></a>

<s cript type=”text/javascript”>
$(document).ready(function() {
$(“.video”).click(function() {
$.fancybox({
‘width’ : 640,
‘height’ : 385,
‘href’ : this.href.replace(new RegExp(“watch\\?v=”, “i”), ‘v/’),
‘type’ : ‘swf’,
‘swf’ : {
‘wmode’ : ‘transparent’,
}
});
return false;
});
});
</script>

References :
http://wpandsuch.com/fancybox-youtube-videos/
http://wpandsuch.com/posts/fancybox-youtube/

Opencart : additional images thumbnail carousel (xml)

<?xml version=”1.0″ encoding=”utf-8″?>
<modification>
<name>Additional Images Thumbnail Carousel</name>
<version>1.0.0</version>
<author>Siew DeLee</author>
<code>additional_images_thumbnail_carousel</code>
<description>Creat carousel for product details page additional images thumbnail carousel</description>

<file path=”catalog/view/theme/*/template/product/product.tpl”>
<operation>
<notes>add id</notes>
<search><![CDATA[<?php foreach ($images as $image) { ?>]]></search>
<add position=”before”><![CDATA[<di v id=”thumbnails”>]]></add>
</operation>

<operation>
<notes></notes>
<search><![CDATA[<li class=”image-additional”><a class=”thumbnail” href=”<?php echo $image[‘popup’]; ?>” title=”<?php echo $heading_title; ?>”> <img src=”<?php echo $image[‘thumb’]; ?>” title=”<?php echo $heading_title; ?>” alt=”<?php echo $heading_title; ?>” /></a></li>
<?php } ?>]]></search>
<add position=”after”><![CDATA[</div>]]></add>
</operation>

<operation>
<notes>add script</notes>
<search position=”before”><![CDATA[<?php echo $footer; ?>]]></search>
<add><![CDATA[<scrip t type=”text/javascript”><!–
$(‘#thumbnails’).owlCarousel({
items: 4,
autoPlay: 3000,
navigation: true,
navigationText: [‘<i class=”fa fa-chevron-left fa-5x”></i>’, ‘<i class=”fa fa-chevron-right fa-5x”></i>’],
pagination: true
});
–></script>]]></add>
</operation>
</file>
</modification>

OpenCart – Affiliate Tracking continue share to Email

/catalog/view/theme/default/template/affiliate/tracking.tpl

<div class=”buttons clearfix”>
<a href=”<?php echo $continue; ?>” class=”btn btn-secondary”>Back</a>
<a id=”share” class=”btn btn-primary”><?php echo $button_continue; ?></a>

‘select’: function(item) {
$(‘#share’).attr(‘href’,’mailto:?Subject=’+item[‘label’]+’&body=’+item[‘value’].replace(/&/g, “%26”));

References :
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_link_mailto
http://stackoverflow.com/questions/5620324/mailto-with-html-body
http://www.rapidtables.com/web/html/mailto.htm
http://stackoverflow.com/questions/23682010/set-a-mailto-link-with-a-subject-containing-an-ampersand

Javascript – replace Character in String

var string = “javascript-replace-dash-with-space”;
var new_string = string.replace(/-/gi,’ ‘);
alert(new_string);

p/s : the i at the end makes the regex case insensitive meaning that it doesn’t matter if the letter it finds is upper- or lower-case.

PHP – object operator “->”

When accessing a method or a property of an instantiated class

class SimpleClass
{
// property declaration
public $var = ‘a default value’;

// method declaration
public function displayVar() {
echo $this->var;
}
}

$a = new SimpleClass();
echo $a->var;
$a->displayVar();


When referring to the attributes of an instantiated object

class a {
public $yourVariable = ‘Hello world!’;

public function returnString() {
return $this->yourVariable;
}
}

$object = new a();
echo $object->returnString();
exit();


Reference : http://stackoverflow.com/questions/3037526/where-do-we-use-the-object-operator-in-php

Joomla – Domain to Sub-directory

Step 1 : create .htaccess file with codes at root :

## RewriteRule ^/?$ “http\:\/\/domain\.com\/index.php” [R=301,L]

RewriteEngine on
# Change domain.com to be your primary domain.
RewriteCond %{HTTP_HOST} ^(www.)?domain.com$

# Change ‘subfolder’ to be the folder you will use for your primary domain.
RewriteCond %{REQUEST_URI} !^/subfolder/

# Don’t change this line.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Change ‘subfolder’ to be the folder you will use for your primary domain.
RewriteRule ^(.*)$ /subfolder/$1

# Change domain.com to be your primary domain again.
RewriteCond %{HTTP_HOST} ^(www.)?domain.com$

# Change ‘subfolder’ to be the folder you will use for your primary domain
# followed by / then the main file for your site, index.php, index.html, etc.
RewriteRule ^(/)?$ subfolder/index.php [L]

Step 2 : Sub-directory htaccess.txt to .htaccess, comments :

# Options +FollowSymLinks

##
# Uncomment following line if your webserver’s URL
# is not directly related to physical file paths.
# Update Your Joomla! Directory (just / for root).
##
# RewriteBase /subfolder

Step 3 : configuration.php :

public $live_site = ‘http://domain.com/‘;

Step 4 : Administrator :

Admin > Global Configuration > Use URL rewriting > Yes

VirtueMart product details add SKU

after : <div class=”vm-product-details-container”>

add :
<!– sku –>
<?php if (!empty($this->product->product_sku)) { ?>
<p>
<?php echo vmText::_(‘COM_VIRTUEMART_PRODUCT_SKU’).’: ‘ ?>
<?php echo $this->product->product_sku ?>
</p>
<?php } ?>
<!– weight –>
<?php if (!empty($this->product->product_weight)) { ?>
<p>
<?php echo vmText::_(‘COM_VIRTUEMART_PRODUCT_WEIGHT’).’: ‘ ?>
<?php echo $this->product->product_weight ?> <?php echo $this->product->product_weight_uom ?>
</p>
<?php } ?>