Skip to content

Instantly share code, notes, and snippets.

@jabes
Last active March 13, 2019 08:03
Show Gist options
  • Save jabes/59534d654e79a932d092c2cfccfcd7e7 to your computer and use it in GitHub Desktop.
Save jabes/59534d654e79a932d092c2cfccfcd7e7 to your computer and use it in GitHub Desktop.
Some commonly used functions in WordPress theme development.
<?php
if (!defined('ABSPATH')) exit("Direct access not permitted.");
define('APP_NAME', 'Viral Startup');
define('APP_SLUG', 'viral-startup');
define('APP_VERSION', SCRIPT_DEBUG ? uniqid() : 1);
define('ASSETS_PATH', get_template_directory() . '/assets/dist');
define('ASSETS_URI', get_template_directory_uri() . '/assets/dist');
require_once 'vendor/autoload.php';
require_once 'wp_helpers.php';
#
# SET PHP TIMEZONE TO MATCH WP SETTINGS
#
$timezone_string = get_option('timezone_string');
if (empty($timezone_string)) $timezone_string = 'UTC';
date_default_timezone_set($timezone_string);
#
# REGISTER WEB ASSETS
#
function remove_default_styles()
{
global $wp_styles;
foreach ($wp_styles->registered as $handle => $data) {
wp_deregister_style($handle);
wp_dequeue_style($handle);
}
}
add_action('wp_enqueue_scripts', 'remove_default_styles', 99);
function remove_default_scripts()
{
global $wp_scripts;
foreach ($wp_scripts->registered as $handle => $data) {
wp_deregister_script($handle);
wp_dequeue_script($handle);
}
}
add_action('wp_enqueue_scripts', 'remove_default_scripts', 99);
function enqueue_theme_styles()
{
wp_enqueue_style('normalize', 'https://cdnjs.cloudflare.com/ajax/libs/normalize/6.0.0/normalize.min.css', null, null);
wp_enqueue_style('flatpickr', 'https://cdnjs.cloudflare.com/ajax/libs/flatpickr/2.4.9/flatpickr.min.css', null, null);
wp_enqueue_style('pannellum', 'https://cdnjs.cloudflare.com/ajax/libs/pannellum/2.3.2/pannellum.css', null, null);
wp_enqueue_style(
APP_SLUG . '-styles',
ASSETS_URI . '/css/app' . (SCRIPT_DEBUG ? '.css' : '.min.css'),
null,
APP_VERSION
);
}
add_action('wp_enqueue_scripts', 'enqueue_theme_styles', 100);
function enqueue_theme_scripts()
{
wp_enqueue_script('vue', 'https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js', null, null, true);
wp_enqueue_script('flatpickr', 'https://cdnjs.cloudflare.com/ajax/libs/flatpickr/2.4.9/flatpickr.min.js', null, null, true);
wp_enqueue_script('pannellum', 'https://cdnjs.cloudflare.com/ajax/libs/pannellum/2.3.2/pannellum.js', null, null, true);
wp_enqueue_style(
APP_SLUG . '-scripts',
ASSETS_URI . '/js/app' . (SCRIPT_DEBUG ? '.js' : '.min.js'),
null,
APP_VERSION,
true
);
if (WP_DEBUG) {
$url = 'http://127.0.0.1:35729/livereload.js';
if (url_exists($url)) {
wp_enqueue_script(APP_SLUG . '-livereload', $url, null, APP_VERSION, true);
}
}
$data = [
'appName' => APP_NAME,
'appVersion' => APP_VERSION,
'assetsUrl' => ASSETS_URI,
'ajaxUrl' => admin_url('admin-ajax.php'),
];
wp_localize_script(APP_SLUG . '-scripts', 'WP', $data);
}
add_action('wp_enqueue_scripts', 'enqueue_theme_scripts', 100);
function enqueue_admin_styles()
{
wp_enqueue_style(
APP_SLUG . '-admin-styles',
ASSETS_URI . '/css/admin' . (SCRIPT_DEBUG ? '.css' : '.min.css'),
null,
APP_VERSION
);
}
add_action('login_enqueue_scripts', 'enqueue_admin_styles');
add_action('admin_enqueue_scripts', 'enqueue_admin_styles');
#
# ADD FAVICON TO ADMIN
#
function add_favicon()
{
$favicon_url = ASSETS_URI . '/favicon.ico';
$favicon_markup = sprintf('<link rel="shortcut icon" href="%s" />', $favicon_url);
echo $favicon_markup;
}
add_action('login_head', 'add_favicon');
add_action('admin_head', 'add_favicon');
#
# ALLOW SVG UPLOADS
#
function custom_upload_mimes($mimes)
{
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'custom_upload_mimes');
#
# REMOVE MENU PAGES
#
function remove_comments_menu()
{
remove_menu_page('edit-comments.php');
}
function remove_acf_menu()
{
if (!WP_DEBUG) {
remove_menu_page('edit.php?post_type=acf-field-group');
}
}
add_action('admin_menu', 'remove_comments_menu', 999);
add_action('admin_menu', 'remove_acf_menu', 999);
#
# DISABLE ADMIN BAR
#
add_filter('show_admin_bar', '__return_false');
#
# REMOVE FLUFF
#
// Remove WordPress emoji scripts
remove_action('wp_head', 'print_emoji_detection_script');
remove_action('wp_print_styles', 'print_emoji_styles');
// Remove WordPress canonical links
remove_action('wp_head', 'rel_canonical');
#
# CUSTOM EXCERPT
#
function custom_excerpt_length()
{
return 75;
}
add_filter('excerpt_length', 'custom_excerpt_length', 999);
function custom_excerpt_more()
{
return '...';
}
add_filter('excerpt_more', 'custom_excerpt_more');
#
# CUSTOM EDITOR STYLESHEET
#
function custom_editor_stylesheet()
{
add_editor_style('style.css');
}
add_action('admin_init', 'custom_editor_stylesheet');
#
# CUSTOM BODY CLASSES
#
function custom_body_classes($classes)
{
global $post;
if ($post) $classes[] = "page-{$post->post_name}";
return $classes;
}
add_filter('body_class', 'custom_body_classes');
<?php
/**
* Embed an SVG
* @param $filename string
* @param $classes array
* @param $sizes array|null
* @return string
*/
function embed_svg($filename, array $classes = [], array $sizes = null)
{
$path = get_image_path("{$filename}.svg");
$svg = file_get_contents($path);
$classes[] = 'svg-container';
$classes[] = $filename;
$attributes = [];
$attributes['class'] = implode(' ', $classes);
if ($sizes) {
$width = $sizes[0];
$height = $sizes[1] ?? $width;
$attributes['style'] = implode('; ', [
"width:{$width}",
"height:{$height}",
]);
}
$attributes = implode(
array_map(
function ($value, $key) {
return sprintf('%s="%s"', $key, $value);
},
array_values($attributes),
array_keys($attributes)
),
' '
);
return "<span {$attributes}>{$svg}</span>";
}
/**
* Function used to create a url friendly slug from any string
* @param $text string The string to convert into a slug
* @return string
*/
function slugify($text)
{
// replace non letter or digits by -
$text = preg_replace('~[^\pL\d]+~u', '-', $text);
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
// trim
$text = trim($text, '-');
// remove duplicate -
$text = preg_replace('~-+~', '-', $text);
// lowercase
$text = strtolower($text);
return $text;
}
/**
* Apply a character limit to a string
* @param string $str String to get an excerpt from
* @param integer $startPos Position int string to start excerpt from
* @param integer $maxLength Maximum length the excerpt may be
* @return string
*/
function char_limit($str, $startPos = 0, $maxLength = 160)
{
$excerpt = $str;
if (strlen($str) > $maxLength) {
$excerpt = substr($str, $startPos, $maxLength - 3);
$lastSpace = strrpos($excerpt, ' ');
$excerpt = substr($excerpt, 0, $lastSpace);
$excerpt .= '...';
}
return $excerpt;
}
/**
* Apply a word limit to a string
* @param string $str The string to get an excerpt from
* @param integer $limit The number of words to allow
* @param string $after A string to append at the end
* @return string
*/
function word_limit($str, $limit = 20, $after = '...')
{
if (str_word_count($str, 0) > $limit) {
$words = str_word_count($str, 2);
$pos = array_keys($words);
$str = substr($str, 0, $pos[$limit]) . $after;
}
return $str;
}
/**
* Generates a human readable timestamp relative to the current time
* @param integer $timestamp The input time used to generate a timestamp relative to now
* @param string $format The date format used when the timestamp provided exceeds a month
* @return string
*/
function relative_timestamp($timestamp, $format = 'M j, Y')
{
if (!ctype_digit($timestamp)) {
$timestamp = strtotime($timestamp);
}
$diff = time() - $timestamp;
if ($diff == 0) {
return 'Now';
} elseif ($diff > 0) {
$day_diff = floor($diff / 86400);
if ($day_diff == 0) {
if ($diff < 60) return 'Just now';
if ($diff < 120) return '1 minute ago';
if ($diff < 3600) return floor($diff / 60) . ' minutes ago';
if ($diff < 7200) return '1 hour ago';
if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
}
if ($day_diff == 1) return 'Yesterday';
if ($day_diff < 7) return $day_diff . ' days ago';
if ($day_diff < 31) return ceil($day_diff / 7) . ' weeks ago';
if ($day_diff < 60) return 'Last month';
return date($format, $timestamp);
} else {
$diff = abs($diff);
$day_diff = floor($diff / 86400);
if ($day_diff == 0) {
if ($diff < 120) return 'In a minute';
if ($diff < 3600) return 'In ' . floor($diff / 60) . ' minutes';
if ($diff < 7200) return 'In an hour';
if ($diff < 86400) return 'In ' . floor($diff / 3600) . ' hours';
}
if ($day_diff == 1) return 'Tomorrow';
if ($day_diff < 4) return date('l', $timestamp);
if ($day_diff < 7 + (7 - date('w'))) return 'Next week';
if (ceil($day_diff / 7) < 4) return 'In ' . ceil($day_diff / 7) . ' weeks';
if (date('n', $timestamp) == date('n') + 1) return 'Next month';
return date($format, $timestamp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment