Code Snippets
A collection of code snippets that I use regularly.
JavaScript
JavaScript Cookies
<script>
function createCookie( name, value, days) {
var expires = "";
if ( days ) {
var date = new Date();
date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie( name ) {
var nameEQ = name + "=";
var ca = document.cookie.split( ';' );
for( var i=0; i < ca.length; i++ ) {
var c = ca[i];
while ( c.charAt(0)==' ' ) c = c.substring( 1, c.length );
if ( c.indexOf( nameEQ ) == 0 ) return c.substring( nameEQ.length, c.length );
}
return null;
}
function eraseCookie( name ) {
createCookie( name, "", -1 );
}
</script>
PHP General
Format U.S. Phone Number
<?php
/* format U.S. phone number */
function tscpl_format_phone( $phone ) {
// strip non-numbers
$phone = preg_replace( '/[^0-9]+/', '', $phone );
if ( strlen( $phone ) < 7 ) { // assume it's an extension
$phone = 'ext ' . $phone;
} elseif ( strlen( $phone ) == 7 ) { // assume it's a 7 digit number nnn-nnnn
preg_match('/(\d{3})(\d{4})/', $phone, $matches);
$phone = "{$matches[1]}-{$matches[2]}";
} elseif ( strlen( $phone ) == 10 ) { // assume area code nnn-nnn-nnnn
preg_match('/(\d{3})(\d{3})(\d{4})/', $phone, $matches);
$phone = "({$matches[1]}) {$matches[2]}-{$matches[3]}";
} elseif ( strlen( $phone ) > 10 ) {
preg_match('/(\d{3})(\d{3})(\d{4})(\d+)/', $phone, $matches);
$phone = "({$matches[1]}) {$matches[2]}-{$matches[3]} ext {$matches[4]}";
}
}
WP Admin
Close First Widget Area in Admin
<?php
add_action( 'admin_footer-widgets.php', function(){
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#widgets-right .widgets-holder-wrap:first').addClass('closed');
});
</script>
<?php
});
Remove Default WordPress Widgets
<?php
function tcw_remove_default_widgets() {
unregister_widget( 'WP_Widget_Pages' );
unregister_widget( 'WP_Widget_Calendar' );
unregister_widget( 'WP_Widget_Archives' );
//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' );
}
add_action( 'widgets_init', 'twc_remove_default_widgets', 11 );
Remove EMOJI support
<?php
add_action( 'init', function () {
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
add_filter( 'emoji_svg_url', '__return_false' );
// Filter to remove TinyMCE emojis
add_filter( 'tiny_mce_plugins', function ( $plugins ) {
if ( is_array( $plugins ) ) {
return array_diff( $plugins, array( 'wpemoji' ) );
}
return array();
});
});
Unregister WordPress Widgets
<?php
/* Unregister WordPress widgets */
function tcw_remove_default_widgets() {
//unregister_widget( 'WP_Nav_Menu_Widget' );
unregister_widget( 'WP_Widget_Pages' );
unregister_widget( 'WP_Widget_Calendar' );
unregister_widget( 'WP_Widget_Archives' );
unregister_widget( 'WP_Widget_Categories' );
unregister_widget( 'WP_Widget_Meta' );
unregister_widget( 'WP_Widget_Recent_Posts' );
unregister_widget( 'WP_Widget_Recent_Comments' );
unregister_widget( 'WP_Widget_RSS' );
unregister_widget( 'WP_Widget_Search' );
unregister_widget( 'WP_Widget_Tag_Cloud' );
//unregister_widget( 'WP_Widget_Text' );
}
add_action( 'widgets_init', 'tcw_remove_default_widgets', 11 );
User - Last Login Date
<?php
// set the last login date
function tcw_set_last_login( $login, $user ) {
$user = get_user_by('login', $login );
$time = current_time( 'timestamp' );
$last_login = get_user_meta( $user->ID, '_last_login', 'true' );
if ( !$last_login ) {
update_usermeta( $user->ID, '_last_login', $time );
} else {
update_usermeta( $user->ID, '_last_login_prev', $last_login );
update_usermeta( $user->ID, '_last_login', $time );
}
}
add_action('wp_login','tcw_set_last_login', 0, 2);
WP Advanced Custom Fields
ACF Front End Forms Shortcode
<?php
//* Add required acf_form_head() function to head of page
function tcw_do_acf_form_head() {
if ( !is_admin() )
acf_form_head();
}
add_action( 'get_header', 'tcw_do_acf_form_head', 1 );
//* Add custom body class to the head
function tcw_acf_form_class( $classes ) {
$classes[] = 'acf-form-front';
return $classes;
}
add_filter( 'body_class', 'tcw_acf_form_class' );
//* ACF Form Short Code
function tcw_sc_acf_form( $attr ) {
$cpt = $attr['cpt'];
$post_id = $_GET['postid'];
$title = ( $attr['title'] == 1 ) || ( $attr['title'] == 'y' ) || ( $attr['title'] == 'yes' );
$content = ( $attr['content'] == 1 ) || ( $attr['content'] == 'y' ) || ( $attr['content'] == 'yes' );
$submit = 'submit';
if ( empty( $post_id ) ) {
$post_id = 'new_post';
} else {
$submit = 'update';
}
$options = array( 'id' => 'acf_form',
'post_id' => $post_id,
'label_placement' => 'left',
'instruction_placement' => 'field',
'new_post' => array( 'post_type' => $cpt, 'post_status' => 'publish'),
'submit_value' => $submit,
'updated_message' => __( 'Client Updated', 'acf' ),
'post_title' => $title,
'post_content' => $content,
'return' => '%post_url%',
);
ob_start();
acf_form( $options );
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
add_shortcode( 'do_acf_form', 'tcw_sc_acf_form' );
Process Default Value Shortcodes
<?php
function tcw_acf_doshortcode( $value, $post_id, $field ) {
return do_shortcode( $value );
}
add_filter('acf/format_value/type=message', 'tcw_acf_doshortcode', 10, 3);
add_filter('acf/load_value/type=message', 'tcw_acf_doshortcode', 10, 3);
WP General
Server Date & Time using WordPress current_time()
<?php
function tcw_serverdate( $dt = 'Y-m-d' ) {
return current_time( $dt );
}
function tcw_servertime( $dt = 'g:ia' ) {
return current_time( $dt );
}
function tcw_serverdatetime( $dt = 'Y-m-d g:ia' ) {
return current_time( $dt );
}
WP Genesis Theme
Remove EDIT link from posts/pages
<?php
/** Remove Edit Link **/
add_filter( 'edit_post_link', '__return_false' );
Unregister Genesis Widgets
<?php
// Unregister Genesis widgets
function unregister_genesis_widgets() {
unregister_widget( 'Genesis_eNews_Updates' );
unregister_widget( 'Genesis_Featured_Page' );
unregister_widget( 'Genesis_Featured_Post' );
unregister_widget( 'Genesis_Latest_Tweets_Widget' );
unregister_widget( 'Genesis_Menu_Pages_Widget' );
unregister_widget( 'Genesis_User_Profile_Widget' );
unregister_widget( 'Genesis_Widget_Menu_Categories' );
}
add_action( 'widgets_init', 'unregister_genesis_widgets', 20 );
WP Shortcodes
Display PHP Date
<?php
// [phpdate format="F j, Y"]
function sc_phpdate( $atts ) {
extract( shortcode_atts( array(
'format' => 'F j, Y'
), $atts ) );
return date( $format );
}
add_shortcode('phpdate', 'sc_php_date');
Display Sidebar Names
<?php
function sc_sidebar_names() {
foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) {
$ret .= $sidebar['id'] . ' -> ' . $sidebar['description'] . '<br />';
}
return $ret;
}
add_shortcode( 'sc_sidebar_info', 'sc_sidebar_names' );
Display the Page ID
<?php
/* [page_id] returns the WordPress Page ID */
function tcw_get_page_id( $atts ) {
return get_the_ID();
}
add_shortcode('page_id', 'tcw_get_page_id');
Get Contents of a URL
<?php
function tcw_sc_wpget( $atts ) {
$url = $atts['url'];
$method = $_SERVER['REQUEST_METHOD'];
if ( strlen( $url ) ) {
if ( $method == 'POST' ) {
$response = wp_remote_post( $url, array( 'timeout' => 120, 'body' => $_POST, 'headers' => array( 'Content-type' => $_SERVER['CONTENT_TYPE'] ) ) );
} else {
$response = wp_remote_get( $url, array( 'timeout' => 120 ) );
}
if ( is_wp_error( $response ) ) {
$ret = 'Error: ' . $response->get_error_message();
} else {
$ret = $response['body'];
}
}
return $ret;
}
add_shortcode( 'wpget', 'tcw_sc_wpget' );
Visitor Details
<?php
/* [user_agent] returns the user's browser info */
function tcw_user_agent( $atts ) {
return $_SERVER['HTTP_USER_AGENT'];
}
add_shortcode('user_agent', 'tcw_user_agent');
/* [remote_addr] returns the user IP address */
function tcw_remote_addr( $atts ) {
return $_SERVER['REMOTE_ADDR'];
}
add_shortcode('remote_addr', 'tcw_remote_addr');