SNHPS
Quick and easy code snippets
no-p-margin.html

Three simple HTML/CSS classes that can be used to remove p tag margins.

<div class="no-last-p-margin">
	<p>Lorem ipsum</p>
	<p>Lorem ipsum</p>
	<p>Lorem ipsum</p>
</div>

<style>
p.no-p-margin,
.no-p-margin p,
p.no-first-p-margin:first-of-type,
.no-first-p-margin p:first-of-type
p.no-last-p-margin:last-of-type,
.no-last-p-margin p:last-of-type
{
	margin: 0;
}
</style>
hide-recaptcha-badge.html

Hide Google's floating reCAPTCHA badge.

<style>
.grecaptcha-badge
{
	display: none!important;
}
</style>
add-event-to-multiple-elements.js

Add an event listener to every element that matches the given selector.

document.querySelectorAll('.snippet-wrapper .snippet-description').forEach(function(event_element)
{
	event_element.addEventListener('click', function(event)
	{
		alert('Element clicked!');
	});
});
add-items-to-array-at-position.js

Clone the given array and add one or more items to the specified position.

function add_items_to_array_at_position(array, index, new_items)
{
    return [...array.slice(0, index), ...new_items, ...array.slice(index)];
}

let old_array = [1,2,5];

let new_array = add_items_to_array_at_position(old_array, 2, [3,4]);

console.log(new_array);

//Output: [1,2,3,4,5]
delegate-event.js

Delegate an event using a parent element and child selector.

function delegate_event(event_type, ancestor_element, target_element_selector, listener_function, args)
{	
	ancestor_element.addEventListener(event_type, function(event)
	{
		let is_direct_match = event.target.matches(target_element_selector);
		let closest_ancestor_match = event.target.closest(target_element_selector);
		
		if (is_direct_match)
		{
			(listener_function)(event, event.target, args);
		}
		
		else if (closest_ancestor_match !== null && ancestor_element.contains(closest_ancestor_match))
		{
			(listener_function)(event, closest_ancestor_match, args);
		}
	});
}

function your_function_here(event, element, args)
{
	alert('foobar!');
}

delegate_event('click', document, '.alert-button', your_function_here, {'foo': 3, 'bar': 'yes'});
document-ready.js

Wait for the document to be ready.

document.addEventListener('DOMContentLoaded', function()
{
	alert('The DOM is now ready to be manipulated!');
});
escape-html.js

Sanitize a string that will be inserted into an HTML document.

function escape_html(string)
{
    return ((string === null) ? null : string.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#039;'));
}
fetch.js

Send a POST request using the new Fetch API.

let form_data = new FormData();
form_data.append('action', 'my_wordpress_ajax_function');
form_data.append('foo', 'bar');

fetch('https://example.com/my_ajax_url', {method: 'POST', headers: {}, body: form_data})
.then
(
	response => response.json()
)
.then
(
	data =>
	{
		console.log(data);
		
		if (data.status === 'success')
		{
			alert('Success!');
		}
		
		else if (data.status === 'error')
		{
			alert('Error...');
		}
		
		else
		{
			throw 'Unexpected response status';
		}
	}
)
.catch(error =>
{
	console.log(error);
	alert('An unknown error occurred. Please try again later or contact us for assistance.');
});
format-numbers.js

Convert a number to a string with the specified number of decimal places and an optional comma.

function format_number(number, num_decimals, include_comma)
{
    return number.toLocaleString('en-US', {useGrouping: include_comma, minimumFractionDigits: num_decimals, maximumFractionDigits: num_decimals});
}

format_number(1234.56789, 2, true); // Returns '1,234.57'
format_number(9001.42, 0, false); // Returns '9001'
get-base64-filesize.js

Calculate the expected filesize of the given base64 string.

function get_base64_filesize(base64)
{
	let content_without_mime = base64.split(",")[1];
	let size_in_bytes = window.atob(content_without_mime).length;
	return size_in_bytes;
}
get-substring.js

Get the text between two substrings, inclusive or exclusive, and optionally trim it afterwards.

function get_substring(full_string, substring_1, substring_2, inclusive, trim)
{
    if (full_string === null) { return null; };

    let substring_1_start = full_string.indexOf(substring_1);
    let substring_2_start = full_string.indexOf(substring_2);
    
    if (substring_1_start === -1 || substring_2_start === -1) { return null; }
    
    let substring_1_end = substring_1_start + substring_1.length;
    let substring_2_end = substring_2_start + substring_2.length;
    
    let return_string = inclusive ? (full_string.substring(substring_1_start, substring_2_end)) : (full_string.substring(substring_1_end, substring_2_start));

    return trim ? return_string.trim() : return_string;
}

//Returns 'and ice'
get_substring('I like cake and ice cream', 'cake', 'cream', false, true);
konami-code.js

Trigger a customizable easter egg when a user inputs the Konami Code with their keyboard arrows or phone swipes.

let Secret=function(t){var e={addEvent:function(t,e,n,o){t.addEventListener?t.addEventListener(e,n,!1):t.attachEvent&&(t["e"+e+n]=n,t[e+n]=function(){t["e"+e+n](window.event,o)},t.attachEvent("on"+e,t[e+n]))},removeEvent:
function(t,e,n){t.removeEventListener?t.removeEventListener(e,n):t.attachEvent&&t.detachEvent(e)},input:"",pattern:"38384040373937396665",keydownHandler:function(t,n){if(n&&(e=n),e.input+=t?t.keyCode:event.keyCode,e.input.length>e.pattern.length
&&(e.input=e.input.substr(e.input.length-e.pattern.length)),e.input===e.pattern)return e.code(e._currentLink),e.input="",t.preventDefault(),!1},load:function(t){this._currentLink=t,this.addEvent(document,"keydown",this.keydownHandler,this),this.iphone.load(t)},unload:
function(){this.removeEvent(document,"keydown",this.keydownHandler),this.iphone.unload()},code:
function(t){window.location=t},iphone:{start_x:0,start_y:0,stop_x:0,stop_y:0,tap:!1,capture:!1,orig_keys:"",keys:["UP","UP","DOWN","DOWN","LEFT","RIGHT","LEFT","RIGHT","TAP","TAP"],input:[],code:function(t){e.code(t)},touchmoveHandler:
function(t){if(1===t.touches.length&&!0===e.iphone.capture){var n=t.touches[0];e.iphone.stop_x=n.pageX,e.iphone.stop_y=n.pageY,e.iphone.tap=!1,e.iphone.capture=!1,e.iphone.check_direction()}},touchendHandler:
function(){if(e.iphone.input.push(e.iphone.check_direction()),e.iphone.input.length>e.iphone.keys.length&&e.iphone.input.shift(),e.iphone.input.length===e.iphone.keys.length)
{for(var t=!0,n=0;n<e.iphone.keys.length;n++)e.iphone.input[n]!==e.iphone.keys[n]&&(t=!1);t&&e.iphone.code(e._currentLink)}},touchstartHandler:
function(t){e.iphone.start_x=t.changedTouches[0].pageX,e.iphone.start_y=t.changedTouches[0].pageY,e.iphone.tap=!0,e.iphone.capture=!0},load:function(t){this.orig_keys=this.keys,e.addEvent(document,"touchmove",this.touchmoveHandler),
e.addEvent(document,"touchend",this.touchendHandler,!1),e.addEvent(document,"touchstart",this.touchstartHandler)},unload:
function(){e.removeEvent(document,"touchmove",this.touchmoveHandler),e.removeEvent(document,"touchend",this.touchendHandler),e.removeEvent(document,"touchstart",this.touchstartHandler)},check_direction:
function(){return x_magnitude=Math.abs(this.start_x-this.stop_x),y_magnitude=Math.abs(this.start_y-this.stop_y),x=this.start_x-this.stop_x<0?"RIGHT":"LEFT",
y=this.start_y-this.stop_y<0?"DOWN":"UP",result=x_magnitude>y_magnitude?x:y,result=!0===this.tap?"TAP":result,result}}};return"string"==typeof t&&e.load(t),"function"==typeof t&&(e.code=t,e.load()),e};"undefined"!=typeof module
&&void 0!==module.exports?module.exports=Secret:"function"==typeof define&&define.amd?define([],function(){return Secret}):window.Secret=Secret;
new Secret(function()
{
	alert('Konami code triggered');
});
trim-and-remove-blank-lines.js

Trim each line in the given string, then remove any blank lines.

function trim_and_remove_blank_lines(string)
{
    return string.replace(/^(?=\n)$|^\s*|\s*$|\n\n+/gm, "")
}

//Returns 'Line 1\nLine2\nLine4'
trim_and_remove_blank_lines("Line 1 \nLine2\r\n\r\nLine4\n")
disk-usage-breakdown.txt

Display the size of each folder and file in the current directory.

#Disk usage
df -h

#Size breakdown of all folders in current directory
sudo du -sh * | sort -rh
find-file-contents.txt

Find all instances of the specified string anywhere in the current folder or its subfolders.

#Case sensitive search
grep -Hrn "foobar"

#Case insensitive search
grep -Hrni "fooBAR"

#Pretty formatting
grep -Hrni "foobar" * --color=always | awk -F: '{print "\n"NR ": " $0}' | awk '{$1=$1};1'

#Limit to 500 characters
grep -Hrni "foobar" * --color=always | awk -F: '{print "\n"NR ": " $0}' | awk '{$1=$1};1' | cut -b 1-400
find-file-or-folder.txt

Locate any files or folders that fully or partially match the given filename.

sudo find . -name "wp-content"
sudo find . -iname "Class-WP-Customize-Section.PHP"
check-public-ip-address.txt

Display the public IP address of the current server.

#Display the IP address of the current device
ip a | grep eth0 | cut -d " " --fields=6 | sed '2q;d' | awk -F'/' '{print $1}'

#Other methods
dig @resolver4.opendns.com myip.opendns.com +short
(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com
drop-large-column.sql

Drop a column from a large table in a relatively timely manner.

SET unique_checks=0;
SET foreign_key_checks=0;
ALTER TABLE table_name DROP COLUMN column_name, algorithm=inplace;
SET unique_checks=1;
SET foreign_key_checks=1;
rename-column.sql

Rename a column in your MySQL table.

ALTER TABLE table_name RENAME COLUMN old_column_name to new_column_name;
echo-json-and-die.php

A convienient helper function for outputting human readable JSON responses.

function echo_json_and_die($data, $status_code)
{
	http_response_code($status_code);
	echo json_encode($data, JSON_PRETTY_PRINT);
	die();
}

echo_json_and_die
([
	'status' => 'error',
	'text_message' => 'Could not find that resource.',
	'html_message' => '<p class="error-message">Could not find that resource.</p>',
], 404);
finish-execution-in-background.php

Continue processing a request after sending back a response and closing the connection.

function close_connection_but_continue_processing($output)
{
    if (function_exists('fastcgi_finish_request'))
    {
        echo $output;
        ignore_user_abort(true); //https://bugs.php.net/bug.php?id=68772
        fastcgi_finish_request();
    }
    
    else
    {
        ob_start();
        echo (empty($output) ? ' ' : $output); //Quirk: At least one character must be outputted for the connection to be closed
        header('Content-Length: ' . ob_get_length());
        header('Connection: close');
        ob_end_flush();
        ob_flush();
        flush();
        session_write_close();
    }
}

close_connection_but_continue_processing('Your request has been received and will now be processed.');
do_long_task();
str-contains-any.php

Check whether the given haystack string contains any of the given needle strings.

function str_contains_any($haystack, $needles, $case_sensitive)
{
    foreach ($needles as $needle)
    {
        if (str_contains($haystack, $needle) || (($case_sensitive === false) && str_contains(strtolower($haystack), strtolower($needle))))
        {
            return true;
        }
    }
    
    return false;
}

$haystack = 'This is a load of shizzle';
$needles = ['fudge', 'shizzle'];
$match_found = str_contains_any($haystack, $needles, true); //true
add-cmd-title.py

Rename the CMD window that's running your Python script.

import os

os.system('title {}'.format('My Python Program'))
create-folder-and-file.py

Create a file, ensure that its folder exists, write some content to it, and save it on demand.

import io
import pathlib

#Files are automatically saved at the end of io.open,
#but you can use this function to save them on demand,
#such as during each iteration of a long loop
def save_file(file):
    file.flush()
    os.fsync(file.fileno())

folder_path = 'lorem/ipsum'
file_name = 'foobar.txt'
file_path = folder_path + '/' + file_name

pathlib.Path(folder_path).mkdir(parents=True, exist_ok=True)

with io.open(file_path, 'a', encoding="utf-8-sig", newline='\n') as log_file:
	log_file.write('blah blah blah')
	save_file(log_file)
create-selenium-webdriver.py

A helper function that lets you create a new Selenium webdriver object with just one line of code.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions

def create_webdriver(browser, width, height, is_headless):
    if (browser == 'firefox'):
        firefox_options = FirefoxOptions()
        firefox_options.add_argument('--width={}'.format(width))
        firefox_options.add_argument('--height={}'.format(height))
        if is_headless:
            firefox_options.add_argument('--headless')
        driver = webdriver.Firefox(executable_path = r"..\..\Selenium\geckodriver.exe", options=firefox_options)

    elif (browser == 'chrome'):
        chrome_options = ChromeOptions()
        chrome_options.add_argument('--window-size={},{}'.format(width, height))
        chrome_options.add_experimental_option('excludeSwitches', ['enable-logging']) #Disable JS/browser messages in CMD
        if is_headless:
            chrome_options.add_argument('--headless')
        driver = webdriver.Chrome(executable_path = r"..\..\Selenium\chromedriver.exe", options=chrome_options)

    driver.set_window_size(width, height) #Fallback option; doesn't work in headless mode

    return driver


driver = create_webdriver('chrome', 1200, 900, False)
csv-output.py

Create a comma-delimited CSV file and sanitize its data.

import io
import pathlib
import time

#Sanitize and shrink the given string so that it will fit into a CSV cell
def sanitize_string_for_csv(string):
    if (string == None):
        return '""'
    string = str(string)
    string = string[:32758]
    string = string.replace('"', '""')
    return ('"' + string + '"')


#Convert an array of strings into a valid CSV row string
def generate_csv_row(cells, include_newline):
    if (isinstance(cells, list) == False):
        raise Exception("The first value passed to generate_csv_row must be a list.")
    if (isinstance(include_newline, bool) == False):
        raise Exception("The second value passed to generate_csv_row must be a bool.")
    row_string = ",".join([sanitize_string_for_csv(cell) for cell in cells])
    if (include_newline == True):
        row_string += '\n'
    return row_string


folder_path = 'exports'
file_name = 'foobar-data-' + time.strftime("%b-%d-%Y-%H%M%S").lower() + '.csv'
file_path = folder_path + '/' + file_name

pathlib.Path(folder_path).mkdir(parents=True, exist_ok=True)

with io.open(file_path, 'a', encoding='utf-8-sig', newline='\n') as csv_file:
    csv_file.write(generate_csv_row(['Header 1', 'Header 2'], True))
    csv_file.write(generate_csv_row(['Foo', 'Bar'], True))
    csv_file.write(generate_csv_row(['Lorem', 'Ipsum'], True))
is-selenium-webdriver-alive.py

Check whether the Selenium webdriver object is still alive and connected to its browser process.

from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException

def is_webdriver_alive(driver):
    print('Checking whether the driver is alive')
    try:
        assert(driver.service.process.poll() == None) #Returns an int if dead and None if alive
        driver.service.assert_process_still_running() #Immediately throws a WebDriverException if dead
        driver.find_element_by_tag_name('html') #Throws a NoSuchElementException if dead
        print('The driver appears to be alive')
        return True
    except (NoSuchElementException, WebDriverException, AssertionError):
        print('The driver appears to be dead')
        return False
    except Exception as ex:
        print('Encountered an unexpected exception type ({}) while checking the driver status'.format(type(ex)))
        return False
		

webdriver_status = is_webdriver_alive(driver)

if (webdriver_status == False):
	try:
		driver.quit()
	except:
		pass
	try:
		print('Attempting to create a new webdriver.')
		driver = create_webdriver()
		print('Successfully created a new webdriver.')
	except:
		print('Failed to create a new webdriver.')
main-wrapper.py

Wrap a Python script's main function with an error handler and pause at the end of the script

import os
import time
import traceback

def main():
    do_stuff()
    do_more_stuff()

if (__name__ == "__main__"):
    try:
        os.system('title {}'.format('My Python Program'))
        main()
        input("\nThe script finished successfully. Press the Enter key to exit.")
    except Exception as ex:
        print('The script crashed at ' + time.ctime() + ' due to an unhandled {} exception.'.format(type(ex)))
        print('Full exception text: ' + str(ex))
        print(traceback.format_exc())
        input("\nPress the Enter key to exit.")
current-year-shortcode.php

Display the current year (2023) by typing [current_year]

function mytheme_handle_current_year_shortcode()
{
	$year = date('Y');
	return $year;
}

add_shortcode('mytheme_current_year', 'mytheme_handle_current_year_shortcode');
debug-wordpress.php

Add these lines to wp-config.php to enable WordPress's debug log file and disable front-end error display

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
disable-wordpress-update-emails.php

Disable the emails that WordPress sends out after automatic updates.

add_filter('auto_core_update_send_email', '__return_false');
add_filter('auto_theme_update_send_email', '__return_false');
add_filter('auto_plugin_update_send_email', '__return_false');
extend-wordpress-login-duration.php

Increase the amount of time that users stay logged in.

//Increase the login session expiration time (by default, it's 2 days, or 14 days if you checked "Remember me")
function extend_wordpress_login_sessions($seconds, $user_id, $remember)
{
	if ($remember)
	{
		$expiration = 90 * 24 * 60 * 60; //Extend remembered sessions to 90 days
	}
	
	else
	{
		$expiration = 15 * 24 * 60 * 60; //Extend non-remembered sessions to 15 days
	}

	return $expiration;
}

add_filter('auth_cookie_expiration', 'extend_wordpress_login_sessions', 99, 3);
wordpress-ajax-call.php

A simple example of a WordPress AJAX call.

function mysite_get_foobar_ajax()
{
	$response =	[
					'status'		=> 'success',
					'text_message'	=> 'The foobar was successful.',
					'html_message'	=> '<p class="success-message">The foobar was successful.</p>',
				];
	echo json_encode($response);
	wp_die();
}

add_action('wp_ajax_mysite_get_foobar_ajax', 'mysite_get_foobar_ajax');

?>


<script>
let form_data = new FormData();
form_data.append('action', 'mysite_get_foobar_ajax');

fetch('/wp-admin/admin-ajax.php', {method: 'POST', headers: {}, body: form_data})
.then
(
	response => response.json()
)
.then
(
	data =>
	{
		console.log(data);
		
		if (data.status === 'success')
		{
			alert(data.text_message);
		}
		
		else if (data.status === 'error')
		{
			alert(data.text_message);
		}
		
		else
		{
			throw 'Unexpected response status';
		}
	}
)
.catch(error =>
{
	console.log(error);
	alert('An unknown error occured.');
});
</script>
wordpress-shortcode.php

Create a simple WordPress shortcode.

/*
* Plugin Name: Custom Foobar Plugin
* Description: Our custom foobar plugin
* Version: 1.0
* Author: Author
* Author URI: https://www.example.com
*/

function handle_foobar_shortcode($original_shortcode_attributes)
{
	$attributes = shortcode_atts([
									'lorem'	=> null,
								],
								$original_shortcode_attributes);
	
	$lorem = $attributes['lorem'] ?? null;
	
	if ($attributes['lorem'] !== 'ipsum')
	{
		return '<p>Error: Unexpected value for "lorem" attribute (expected "ipsum").</p>';
	}
	
	$output_html = '<p>The shortcode works!</p>';
	
	return $output_html;
}

add_shortcode('foobar', 'handle_foobar_shortcode');
wordpress-show-all-hooks.php

Output the hook name of every WordPress filter/action being used.

$debug_tags = array();

add_action('all', function ($tag)
{
    global $debug_tags;
    if (in_array($tag, $debug_tags))
	{
        return;
    }
    echo "<pre>" . $tag . "</pre>";
    $debug_tags[] = $tag;
});

This website is owned and operated by SiteBolts. All the code snippets found here are intended to be a starting point and should not be treated as a perfect solution to every problem. We do not guarantee the performance, reliability, or security of the code found on this website. As always, you should ensure that you have adequate backups before adding, changing, or executing any code.