Append url parameters to links with classname #Javascript
//Append url parameters to links with classname
(function() {
var domainsToDecorate = ['domain.com'], queryParams = ['utm_medium','utm_source','utm_campaign','utm_term','utm_content'];
var links = document.querySelectorAll('.rewrite-url'); 
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
 for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) { 
   if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
	 links[linkIndex].href = decorateUrl(links[linkIndex].href);
   }
 }
}
function decorateUrl(urlToDecorate) {
 urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
 var collectedQueryParams = [];
 for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
   if (getQueryParam(queryParams[queryIndex])) {
	 collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
   }
 }
 return urlToDecorate + collectedQueryParams.join('&');
}
function getQueryParam(name) {
 if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(window.location.search))
   return decodeURIComponent(name[1]);
}
Hubspot Form Callbacks #Hubspot
// https://legacydocs.hubspot.com/global-form-events
// onBeforeFormInit - onFormReady - onFormSubmit - onFormSubmitted
window.addEventListener('message', event => {
 if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
  // Form Ready
 } else if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormSubmit') {
  // Form Submit
 }
});
User Creation Callback #woocommerce
// define the woocommerce_created_customer callback 
function action_woocommerce_created_customer( $customer_id, $new_customer_data, $password_generated ) { 
    // make action magic happen here... 
};
// add the action 
add_action( 'woocommerce_created_customer', 'action_woocommerce_created_customer', 10, 3 ); 
Custom Button Shortcode #wordpress
// functions.php
function custom_button_shortcode( $atts, $content = null ) {
	extract( shortcode_atts( array(
		'url'    => '',
		'title'  => '',
		'target' => '',
		'text'   => '',
	), $atts ) );
	$content = $text ? $text : $content;
	if ( $url ) {
		$link_attr = array(
			'href'   => esc_url( $url ),
			'title'  => esc_attr( $title ),
			'target' => ( 'blank' == $target ) ? '_blank' : '',
			'class'  => 'custombutton'
		);
		$link_attrs_str = '';
		foreach ( $link_attr as $key => $val ) {
			if ( $val ) {
				$link_attrs_str .= ' ' . $key . '="' . $val . '"';
			}
		}
		return '<a' . $link_attrs_str . '>' . do_shortcode( $content ) . '</a>';
	} else {
		return '<span class="custombutton"><span>' . do_shortcode( $content ) . '</span></span>';
	}
}
add_shortcode( 'custombutton', 'custom_button_shortcode' );
function register_button( $buttons ) {
   array_push( $buttons, "|", "custombutton" );
   return $buttons;
}
function add_plugin_custom_button( $plugin_array ) {
	$plugin_array['custombutton'] = get_template_directory_uri() . '/js/custombutton.js';
   return $plugin_array;
}
function my_custom_button_shortcode() {
   if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') ) {
	  return;
   }
   if ( get_user_option('rich_editing') == 'true' ) {
	  add_filter( 'mce_external_plugins', 'add_plugin_custom_button' );
	  add_filter( 'mce_buttons', 'register_button' );
   }
}
add_action('init', 'my_custom_button_shortcode');
// custombutton.js
(function() {
   tinymce.create('tinymce.plugins.custombutton', {
	  init : function(ed, url) {
		 ed.addButton('custombutton', {
			title : 'Custom Button',
			image : url+'/custombutton.svg',
			onclick : function() {
			   	var href = prompt("Href", "https://go.merlinleonard.com/");
				var title = prompt("Title", "Call to Action");
				var target = prompt("Target", "_blank");
				ed.execCommand('mceInsertContent', false, '[custombutton url="'+href+'" target="'+target+'" text="'+title+'"]');
			}
		 });
	  },
	  createControl : function(n, cm) {
		 return null;
	  },
	  getInfo : function() {
		 return {
			longname : "Custom Button",
			author : 'Otowui.com',
			authorurl : 'https://www.otowui.com',
			version : "1.0"
		 };
	  }
   });
   tinymce.PluginManager.add('custombutton', tinymce.plugins.custombutton);
})();
// custombutton.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M384 32H64C28.65 32 0 60.65 0 96v320c0 35.34 28.65 64 64 64h320c35.35 0 64-28.66 64-64V96C448 60.65 419.3 32 384 32zM330.5 323.9c0 6.473-3.889 12.3-9.877 14.78c-5.979 2.484-12.86 1.105-17.44-3.469l-45.25-45.25l-67.92 67.92c-12.5 12.5-32.72 12.46-45.21-.0411l-22.63-22.63C109.7 322.7 109.6 302.5 122.1 289.1l67.92-67.92L144.8 176.8C140.2 172.2 138.8 165.3 141.3 159.4c2.477-5.984 8.309-9.875 14.78-9.875h158.4c8.835 0 15.1 7.163 15.1 15.1V323.9z"/></svg>
Custom Image Shortcode #wordpress
//functions.php
function customimage_shortcode( $atts, $content = null ) {
	extract( shortcode_atts( array(
		'url'    => '',
		'text'   => '',
	), $atts ) );
	$imgurl = $url ? $url : $imgurl;
	$content = $text ? $text : $content;
	if ( $url ) {
		foreach ( $link_attr as $key => $val ) {
			if ( $val ) {
				$link_attrs_str .= ' ' . $key . '="' . $val . '"';
			}
		}
		return '<figure class="customimage"><img src="' . $imgurl . '"/><figcaption>' . do_shortcode( $content ) . '</figcaption></figure>';
		
	}
}
add_shortcode( 'customimage', 'customimage_shortcode' );
function register_customimage( $buttons ) {
   array_push( $buttons, "", "customimage" );
   return $buttons;
}
function add_plugin_customimage( $plugin_array ) {
	$plugin_array['customimage'] = get_template_directory_uri() . '/js/customimage.js';
   return $plugin_array;
}
function my_customimage_shortcode() {
   if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') ) {
	  return;
   }
   if ( get_user_option('rich_editing') == 'true' ) {
	  add_filter( 'mce_external_plugins', 'add_plugin_customimage' );
	  add_filter( 'mce_buttons', 'register_customimage' );
   }
}
add_action('init', 'my_customimage_shortcode');
// customimage.js
(function() {
   tinymce.create('tinymce.plugins.customimage', {
	  init : function(ed, url) {
		 ed.addButton('customimage', {
			title : 'Custom Image',
			image : url+'/customimage.svg',
			onclick : function() {
				var title = prompt("Text", "Call to Action");
				var target = prompt("Target", "_blank");
				ed.execCommand('mceInsertContent', false, '[customimage url="'+href+'" text="'+title+'"]');
			}
		 });
	  },
	  createControl : function(n, cm) {
		 return null;
	  },
	  getInfo : function() {
		 return {
			longname : "Custom Image",
			author : 'Otowui.com',
			authorurl : 'https://www.otowui.com',
			version : "1.0"
		 };
	  }
   });
   tinymce.PluginManager.add('customimage', tinymce.plugins.customimage);
})();
// customimage.svg
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 448 512" style="enable-background:new 0 0 448 512;" xml:space="preserve"><path d="M146.7,228.1l-46.7,64c-3.5,4.9-4.1,11.3-1.3,16.7c2.8,5.3,7.4,8.7,14.3,8.7h224c5.9,0,11.3-3.2,14.1-8.4 c2.8-5.2,2.5-11.5-0.8-16.4l-85.3-128c-3-4.4-8-7.1-13.3-7.1s-10.4,2.7-13.3,7.1l-53.6,80.3l-12.2-16.8c-3-4.2-7.8-6.6-12.9-6.6 S149.8,223.9,146.7,228.1z M401,29.5H49c-26.4,0-48,21.6-48,48v352c0,26.4,21.6,48,48,48h352c26.4,0,48-21.6,48-48v-352 C449,51.1,427.4,29.5,401,29.5z M385,349.5H65v-256h320V349.5z M129,189.5c17.6,0,32-14.4,32-32s-14.4-32-32-32s-32,14.4-32,32 S111.4,189.5,129,189.5z"/></svg>
Fetch .json file #Javascript
function fetchJSONFile(path, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                if (callback) callback(data);
            }
        }
    };
    httpRequest.open('GET', path);
    httpRequest.send(); 
}

fetchJSONFile('file.json', function(data){
	// Do something with Data
    console.log(data);
});
Unregister widgets #wordpress
// unregister all widgets
function unregister_default_widgets() {
	unregister_widget('WP_Widget_Pages');
	unregister_widget('WP_Widget_Calendar');
	unregister_widget('WP_Widget_Archives');
	unregister_widget('WP_Widget_Links');
	unregister_widget('WP_Widget_Meta');
	unregister_widget('WP_Widget_Search');
	unregister_widget('WP_Widget_Text');
	unregister_widget('WP_Widget_Categories');
	unregister_widget('WP_Widget_Recent_Posts');
	unregister_widget('WP_Widget_Recent_Comments');
	unregister_widget('WP_Widget_RSS');
	unregister_widget('WP_Widget_Tag_Cloud');
	unregister_widget('WP_Nav_Menu_Widget');
	unregister_widget('Twenty_Eleven_Ephemera_Widget');
	unregister_widget('WP_Widget_Media_Audio');
	unregister_widget('WP_Widget_Media_Image');
	unregister_widget('WP_Widget_Media_Video');
	//unregister_widget('WP_Widget_Custom_HTML');
}
add_action('widgets_init', 'unregister_default_widgets', 11);
Pdo Query for noobs #PHP
<?php
// Set
global $pdo;
if (isset($pdo)) {return;} 
mysqli_report(MYSQLI_REPORT_STRICT);
$pdo = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
// Set the PDO::ATTR_EMULATE_PREPARES Attribute to false
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
if (mysqli_connect_errno()) {		
  die(sprintf("Connect failed: %s\n", mysqli_connect_error()));
}
// Prepared Statements
$firstname = "bruce";
$sql = "SELECT * FROM users WHERE firstname =:fname ;";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":fname", $firstname);
$stmt->execute();
if(!$result = $stmt->fetch(PDO::FETCH_OBJ)){
    echo "Credentials do no match";
} else {
    echo"Id: ".$result->id. " Name: ".$result->firstname." ".$result->lastname;
}
// Prepared Statements With Parameterized Query
$firstname = "jeff";
$sql = "SELECT * FROM users WHERE firstname = ?";
$stmt = $pdo->prepare($sql);
$stmt->bind_param("s", $firstname);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) exit('No rows');
while($row = $result->fetch_assoc()) {
    echo"Id: ".$row['id']. " Name: ".$row['firstname']." ".$row['lastname'];
}
get http headers values #PHP
<?php 			
// GET HTTP HEADERS VALUES
// SINGLE VALUE - Replace XXXXXX_XXXX with the name of the header you need in UPPERCASE (and with '-' replaced by '_')
$headerStringValue = $_SERVER['HTTP_XXXXXX_XXXX'];
echo $headerStringValue;
// GET ALL HEADERS			
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
} ?>
Trim Input Whitespace #Javascript
/* trim-whitespace-input.js*/
$('.no-spaces-field').keyup(function() {
  $(this).val($(this).val().replace(/ +?/g, ''));
});
Bulletproof Buttons #Email
<center>
<div style="margin: 0 auto;"><!--[if mso]>
 <v:rect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="#" style="height:50px;v-text-anchor:middle;width:250px;" arcsize="16%" strokecolor="#ed7014" fill="t">
    <v:fill type="tile" src="https://www.emailonacid.com/images/orange_btn_bg.jpg" color="#ed7014" />
    <w:anchorlock/>
    <center style="color:#ffffff;font-family:sans-serif;font-size:18px;font-weight:bold;">Click the Button!</center>
  </v:rect>
<![endif]-->
<div style="margin: 0 auto;mso-hide:all;">
<table align="center" cellpadding="0" cellspacing="0" height="50" width="250" style="margin: 0 auto; mso-hide:all;">
	<tbody>
		<tr>
			<td align="center" bgcolor="#ed7014" height="50" style="vertical-align:middle;color: #ffffff; display: block;background-color:#ed7014;background-image:url(https://www.emailonacid.com/images/orange_btn_bg.jpg);border:1px solid #ed7014;mso-hide:all;" width="250">
				<a class="cta_button" href="#" style="font-size:16px;-webkit-text-size-adjust:none; font-weight: bold; font-family:sans-serif; text-decoration: none; line-height:50px; width:250px; display:inline-block;" title="Button">
					<span style="color:#ffffff">Click the Button!</span>
				</a>
			</td>
		</tr>
	</tbody>
</table>
</div>
</div>
</center>
Force Https the easy way #Html
<!-- Force https -->
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
Plesk increase timeout ( 504 Gateway Time-out) #Server
# Plesk increase timeout response( 504 Gateway Time-out)
# Domains > example.com > Apache & nginx Settings.
FcgidIdleTimeout 1200
FcgidProcessLifeTime 1200
FcgidConnectTimeout 1200
FcgidIOTimeout 1200
Timeout 1200
ProxyTimeout 1200
Conditional content hiding with Outlook #Email
<!--[if mso]>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
    <tr>
        <td>Outlook content</td>
    </tr>
</table>
<![endif]-->

<table border="0" cellpadding="0" cellspacing="0" width="100%" style="mso-hide:all;">
    <tr>
        <td>Other clients</td>
    </tr>
</table>
Download Textarea Content as Html File #Javascript
/* Download Textarea Content as Html File.js */
$('#download-button').click(function() {
    if ('Blob' in window) {
        var fileName = prompt('Please enter file name to save', 'Untitled.html');
        if (fileName) {
            var textValue = $('textarea').html();
            var textToWrite = htmlDecode(textValue);
            var textFileAsBlob = new Blob([textToWrite], {
                type: 'application/xhtml+xml'
            });
            if ('msSaveOrOpenBlob' in navigator) {
                navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
            } else {
                var downloadLink = document.createElement('a');
                downloadLink.download = fileName;
                downloadLink.innerHTML = 'Download File';
                if ('webkitURL' in window) {
                    downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
                } else {
                    downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
                    downloadLink.click(function() {
                        document.body.removeChild(event.target);
                    });
                    downloadLink.style.display = 'none';
                    document.body.appendChild(downloadLink);
                }
                downloadLink.click();
            }
        }
    } else {
        alert('Your browser does not support the HTML5 Blob.');
    }
});
Pass UTMs to iframe src #Javascript
// Iframe Container
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
jQuery(function() {
	var oldIframe = jQuery('#iframe');
	if (oldIframe.length) {
		var src = oldIframe.attr('src');
		if (src) {
			var iframeContent = $('<iframe id="iframe-new" src="' + src + location.search + '" style="border: none;width: 100%;background-color:#fff;"></iframe>');
			oldIframe.replaceWith(iframeContent);
		}
	}
});
</script>
<iframe id="iframe" src="https://go.domain.com/form.html"></iframe>
Reorder Admin Menu #wordpress
// REORDER MENU
add_filter('custom_menu_order', function() { return true; });
add_filter('menu_order', 'my_new_admin_menu_order');
function my_new_admin_menu_order( $menu_order ) {
  $new_positions = array('index.php' => 1, 'edit.php' => 2, 'upload.php' => 7, 'edit.php?post_type=page' => 3, 'edit-comments.php' => 8);
  function move_element(&$array, $a, $b) {
    $out = array_splice($array, $a, 1);
    array_splice($array, $b, 0, $out);
  }
  foreach( $new_positions as $value => $new_index ) {
    if( $current_index = array_search( $value, $menu_order ) ) {
      move_element($menu_order, $current_index, $new_index);
    }
  }
  return $menu_order;
};
Create iFrame from Textarea Content Html #Javascript
/* Create iFrame from Textarea Content Html */
function setFrame() {
    var HTMLval = TextareaContentID.value;
    var iframe = document.getElementById('iframeID');
    iframe.contentWindow.document.open();
    iframe.contentWindow.document.write(HTMLval);
    iframe.contentWindow.document.close();
}
Change add to cart text on archives depending on product type #woocommerce
// Change add to cart text on archives depending on product type
add_filter( 'woocommerce_product_add_to_cart_text' , 'custom_woocommerce_product_add_to_cart_text' );
function custom_woocommerce_product_add_to_cart_text() {
	global $product;
	$product_type = $product->product_type;
	switch ( $product_type ) {
		case 'external':
			return __( 'Add to cart', 'woocommerce' );
		break;
		case 'grouped':
			return __( 'Add to cart', 'woocommerce' );
		break;
		case 'simple':
			return __( 'Add to cart', 'woocommerce' );
		break;
		case 'variable':
			return __( 'Add to cart', 'woocommerce' );
		break;
		default:
			return __( 'Add to cart', 'woocommerce' );
	}
	
};
Post per page for Custom post types #wordpress
<?php /* Set posts per page for a custom post type in wordpress.php */ ?>
<?php
function set_posts_per_page_for_towns_cpt( $query ) {
  if ( !is_admin() && $query->is_main_query() && is_post_type_archive( 'towns' ) ) {
    $query->set( 'posts_per_page', '10' );
  }
}
add_action( 'pre_get_posts', 'set_posts_per_page_for_towns_cpt' );
?>
Add Custom post types to tags and categories archives #wordpress
// Add Custom post types to tags and categories archives
function add_cpts_to_archive_page( $query ) {
  if( (is_category() || is_tag()) && $query->is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
	$query->set( 'post_type', array(
	 'post', 'custom-post-type-1', 'custom-post-type-2'
		));
	}
	return $query;
}
add_filter( 'pre_get_posts', 'add_cpts_to_archive_page' );
Show thumbnails in pagination #wordpress
<?php /* Show thumbnails in WordPress Posts Pagination */ ?>
<?php if( $prev_post = get_previous_post() ): ?>
    <div class="nav-box previous">
        <?php $prevthumbnail = get_the_post_thumbnail($prev_post->ID, 'thumbnail' );?>
        <?php previous_post_link('%link',"$prevthumbnail  <p>%title</p>", TRUE); ?>
    </div>
<?php endif; ?>
<?php if( $next_post = get_next_post() ): ?>
    <div class="nav-box next">
        <?php $nextthumbnail = get_the_post_thumbnail($next_post->ID, 'thumbnail' );  ?>
        <?php next_post_link('%link',"$nextthumbnail  <p>%title</p>", TRUE); ?>
    </div>
<?php endif; ?>
Hide WooCommerce Cart Icon When Empty #woocommerce
// Hide WooCommerce Cart Icon When Empty
add_action( 'wp_footer', function() {
	if ( WC()->cart->is_empty() ) {
		echo '<style type="text/css">.head-cart{ display: none; }</style>';
	}
});

No more items to load