Skip to content

Instantly share code, notes, and snippets.

@strsar
Created October 7, 2021 01:42
Show Gist options
  • Save strsar/4112514977849b566fe9a0f946b1ae06 to your computer and use it in GitHub Desktop.
Save strsar/4112514977849b566fe9a0f946b1ae06 to your computer and use it in GitHub Desktop.
[WP] Good start to some helper functions w/ lazy loading functions over WP's default...
<?php defined( 'ABSPATH' ) or header( 'Location: /' );
/**
* Helper and utility functions
*/
/**
* Get only excerpt content, not post intro
*/
function get_only_the_excerpt() {
global $post;
return $post->post_excerpt;
}
/**
* Get post parent
*/
function get_post_parent_id() {
global $post;
if($post) {
$current = $post->ID;
return $post->post_parent;
}
}
/**
* Param notracking
*/
function render_tracking_scripts() {
if(isset($_GET['notrack'])){
return false;
}
return true;
}
/**
* Filter punctuation
*/
function __punct($text) {
$punct = array(
'.',
':'
);
$filter = substr($text, -1);
if(in_array($filter, $punct)) {
$text = rtrim($text, $filter).'<span class="text-primary">'.$filter.'</span>';
}
return $text;
}
/**
* Filter solutions brand title display Nex[Title]
*/
function __brands($text, $bold = true) {
$brands = get_posts([
'fields' => 'ids',
'post_type' => 'solution',
'post_status' => 'publish',
'numberposts' => -1,
]);
$titles = [];
$filterd_titles = [];
foreach($brands as $brand){
$titles[] = get_the_title($brand);
}
if($bold){
foreach($brands as $brand){
$filtered_titles[] = str_replace('Nex', '<b>Nex</b>', get_the_title($brand));
}
}else{
foreach($brands as $brand){
$prefix = 'Nex';
$parts = explode($prefix, get_the_title($brand));
if(isset($parts[1])){
$filtered_titles[] = $prefix.'<span class="fw-normal">'.$parts[1].'</span>';
continue;
}
$filtered_titles[] = get_the_title($brand);
}
}
$text = str_replace($titles, $filtered_titles, $text);
return $text;
}
/**
* Fixes CSS layout and repaint for when images are loaded
*/
function img_lazy_src($width = '3', $height = '2') {
return "data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20".$width."%20".$height."'%3E%3C/svg%3E";
}
/**
* ID: All the img data you'll ever need
*/
function img_src_data($img, $size = 'large') {
$img_id = $img['ID'] ? $img['ID'] : get_post_thumbnail_id();
$alt = $img['alt'] ? $img['alt'] : get_thumb_img_alt($img['id']);
$width = $img['width'];
$height = $img['height'];
$src = 'src="'.img_lazy_src($width, $height).'"';
$data_src = 'data-src="'.wp_get_attachment_image_url($img_id, $size).'"';
$data_srcset = wp_get_attachment_image_srcset($img_id, $size) ? 'data-srcset="'.wp_get_attachment_image_srcset($img_id, $size).'"' : '';
//$sizes = 'sizes="'.wp_get_attachment_image_sizes($img_id, $size).'"';
return $src.' '.$data_src.' '.$data_srcset.' width="'.$width.'" height="'.$height.'" alt="'.$alt.'"';
}
/**
* POST: All the img data you'll ever need
*/
function post_img_src_data($img_id = '', $size = 'large') {
$img_id = $img_id ? $img_id : get_post_thumbnail_id();
$img_meta = wp_get_attachment_metadata($img_id);
$width = $img_meta['width'] ?? '';
$height = $img_meta['height'] ?? '';
if(isset($img_meta['sizes'][$size])) {
$width = $img_meta['sizes'][$size]['width'] ?? $img_meta['width'];
$height = $img_meta['sizes'][$size]['height'] ?? $img_meta['height'];
}
$src = 'src="'.img_lazy_src($width, $height).'"';
$data_src = 'data-src="'.wp_get_attachment_image_url($img_id, $size).'"';
$data_srcset = wp_get_attachment_image_srcset($img_id, $size) ? 'data-srcset="'.wp_get_attachment_image_srcset($img_id, $size).'"' : '';
$width = $width ? 'width="'.$width.'" ' : '';
$height = $height ? 'height="'.$height.'" ' : '';
return $src.' '.$data_src.' '.$data_srcset.''.$width.''.$height.'alt="'.get_thumb_img_alt($img_id).'"';
}
/**
* FEATURED: All the img data you'll ever need... (w/o lazy loading)
*/
function featured_img_src_data($img_id = '', $size = 'large') {
$img_id = $img_id ? $img_id : get_post_thumbnail_id();
$img_meta = wp_get_attachment_metadata($img_id);
$width = $img_meta['width'] ?? '';
$height = $img_meta['height'] ?? '';
if(isset($img_meta['sizes'][$size])) {
$width = $img_meta['sizes'][$size]['width'] ?? $img_meta['width'];
$height = $img_meta['sizes'][$size]['height'] ?? $img_meta['height'];
}
$src = 'src="'.wp_get_attachment_image_url($img_id, $size).'"';
$srcset = wp_get_attachment_image_srcset($img_id, $size) ? 'srcset="'.wp_get_attachment_image_srcset($img_id, $size).'"' : '';
$width = $width ? 'width="'.$width.'" ' : '';
$height = $height ? 'height="'.$height.'" ' : '';
return $src.' '.$srcset.''.$width.''.$height.'alt="'.get_thumb_img_alt($img_id).'"';
}
/**
* STACK: All the img data you'll ever need (no lazy loading)
*/
function stack_img_src_data($img_id = '', $size = 'large') {
$img_id = $img_id ? $img_id : get_post_thumbnail_id();
$img_meta = wp_get_attachment_metadata($img_id);
$width = $img_meta['width'] ?? '';
$height = $img_meta['height'] ?? '';
if(isset($img_meta['sizes'][$size])) {
$width = $img_meta['sizes'][$size]['width'] ?? $img_meta['width'];
$height = $img_meta['sizes'][$size]['height'] ?? $img_meta['height'];
}
$data_src = 'src="'.wp_get_attachment_image_url($img_id, $size).'"';
$data_srcset = wp_get_attachment_image_srcset($img_id, $size) ? 'srcset="'.wp_get_attachment_image_srcset($img_id, $size).'"' : '';
return $data_src.' '.$data_srcset.' width="'.$width.'" height="'.$height.'" alt="'.get_thumb_img_alt($img_id).'"';
}
/**
* Get thumb alt
*/
function get_thumb_img_alt($id = '') {
$att_id = $id ? $id : get_post_thumbnail_id(get_the_ID());
$alt = get_post_meta($att_id, '_wp_attachment_image_alt', true) ? get_post_meta($att_id, '_wp_attachment_image_alt', true) : get_the_title($id);
return esc_attr(trim(strip_tags($alt)));
}
/**
* SVG include
*/
function include_svg($file){
$url = $file['url'] ? $file['url'] : $file;
$file = str_replace(home_url('/'), ABSPATH, $url);
if(file_exists($file)){
include($file);
}
}
/**
* Get post tags
*/
function get_post_tags() {
$tags = get_the_tags();
if($tags) {
$output = '<ul class="nav nav-tags">';
foreach($tags as $tag) {
$output .= '<li class="nav-item"><a class="nav-link" href="'.get_term_link($tag->slug, $tag->taxonomy).'">'.$tag->name.'</a></li>';
}
$output .= '</ul>';
return $output;
}
}
/**
* Get post cats
*/
function get_post_categories($id, $classes = '') {
$id = $id ? $id : get_the_ID();
$cats = wp_get_post_categories($id);
$classes = $classes ? ' '.$classes : '';
if($cats) {
$output = array();
foreach($cats as $cat) {
$output[] = '<a class="breadcrumb-item'.$classes.'" href="'.get_term_link($cat, 'category').'">'.get_cat_name($cat).'</a>';
}
$output = join('', $output);
return $output;
}
}
/**
* Get current url (needed for non-page post types AKA: careers)
*/
function current_url() {
global $wp;
$current_url = home_url(add_query_arg(array(), $wp->request).'/');
return esc_url($current_url);
}
/**
* Pagination
*/
function pagination() {
global $wp_query;
if(wp_is_mobile()) {
$prev_text = __('<i class="far fa-chevron-left text-sm"></i>');
$next_text = __('<i class="far fa-chevron-right text-sm"></i>');
}else{
$prev_text = __('<i data-bs-toggle="tooltip" data-placement="left" title="'.__('Previous page').'" class="far fa-chevron-left text-sm"></i>');
$next_text = __('<i data-bs-toggle="tooltip" data-placement="right" title="'.__('Next page').'" class="far fa-chevron-right text-sm"></i>');
}
$html = ob_start();
$pagination = paginate_links(
array(
'type' => 'array',
'base' => str_replace(PHP_INT_MAX, '%#%', esc_url(get_pagenum_link(PHP_INT_MAX))).'#paged',
'format' => '?paged=%#%',
'current' => get_query_var('paged') ? intval(get_query_var('paged')) : 1,
'total' => $wp_query->max_num_pages,
'mid_size' => 1,
'end_size' => 2,
//'prev_next' => false,
'prev_text' => $prev_text,
'next_text' => $next_text,
)
);
if(!empty($pagination)) : ?>
<div class="container-fluid pt-4 mt-4 mb-n4">
<ul class="pagination justify-content-center mb-1">
<?php foreach($pagination as $key => $page_link) : ?>
<li class="page-item<?php echo (strpos($page_link, 'current') !== false) ? ' active' : ''; ?>"><?php echo str_replace('page-numbers', 'page-link', $page_link); ?></li>
<?php endforeach; ?>
</ul>
<div class="text-black-50 text-sm text-center mb-0 line-height-sm">
<?php echo __('Page'); ?> <b><?php echo max(1, get_query_var('paged')); ?></b> <?php echo __('of'); ?> <b><?php echo $wp_query->max_num_pages; ?></b>
</div>
</div>
<?php endif; ?>
<?php
$html = ob_get_clean();
$html = str_replace('page/1/#paged', '', $html);
return $html;
}
if( ! function_exists( 'get_partial' ) ) {
/**
* Get a template partial and pass data to it...
*
* @param $template
* @param array $data
*/
function get_partial( $template, $data = [] ) {
extract( $data );
$paths = [];
$templates = ! is_array( $template ) ? [ $template ] : $template;
foreach( $templates as $template ) {
$paths[] = SHARED_DIR . '/' . $template . '.php';
}
include( locate_template( $paths, false, false ) );
}
}
if( ! function_exists( 'map' ) ) {
function map($items, $func) {
$result = [];
foreach($items as $key => $value) {
$result[$key] = $func($value, $key);
}
return $result;
}
}
if( ! function_exists( 'get_field_or_option' ) ) {
/**
* Get a customized field/subfield value or default option value...
*
* @param $field_name
* @param $post
* @param bool $customize Some fields have a condition to overwrite or not
*
* @return bool|mixed
*/
function get_field_or_option( $field_name, $post, $customize = true ) {
if( $customize ) {
if( $field = get_field( $field_name, $post ) ) {
return $field;
} elseif( $field = get_sub_field( $field_name, $post ) ) {
return $field;
}
}
return get_field( $field_name, 'option' );
}
}
/**
* Recursively get taxonomy and its children
*
* @param string $taxonomy
* @param int $parent - parent term id
* @return array
*/
function get_taxonomy_hierarchy($taxonomy, $parent = 0) {
$taxonomy = is_array($taxonomy) ? array_shift($taxonomy) : $taxonomy;
$cat_order = 'DESC';
if(is_polylang_active()) {
$cat_order = pll_current_language() == pll_default_language() ? 'DESC' : 'ASC'; // Reverse order if not EN
}
$ordering = $parent == 0 ? $cat_order : 'ASC';
$terms = get_terms($taxonomy, array('parent' => $parent, 'hide_empty' => false, 'orderby' => 'name', 'order' => $ordering));
$children = array();
foreach($terms as $term){
$term->children = get_taxonomy_hierarchy($taxonomy, $term->term_id);
$children[$term->term_id] = $term;
}
return $children;
}
/**
* Recursively get all taxonomies as complete hierarchies
*
* @param $taxonomies array of taxonomy slugs
* @param $parent int - Starting parent term id
*
* @return array
*/
function get_taxonomy_hierarchy_multiple( $taxonomies, $parent = 0 ) {
if ( ! is_array( $taxonomies ) ) {
$taxonomies = array( $taxonomies );
}
$results = array();
foreach( $taxonomies as $taxonomy ){
$terms = get_taxonomy_hierarchy( $taxonomy, $parent );
if ( $terms ) {
$results[ $taxonomy ] = $terms;
}
}
return $results;
}
/**
* Get the latest posts...
*
* @param bool $category
* @param bool $tag
* @param bool $exclude
* @param int $limit
*
* @return int[]|\WP_Post[]
*/
function get_latest_posts( $category = false, $tag = false, $exclude = false, $limit = 3 ) {
return get_posts( [
'fields' => 'ids',
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => $limit,
'category' => $category,
'tag_id' => $tag,
'post__not_in' => [ $exclude ],
'suppress_filters' => false,
//'lang' => 'en',
] );
}
/**
* Get the primary term of a post, by taxonomy...
*
* @notes If Yoast Primary Term is used, return it, otherwise fallback to the first term.
*
* @param string $taxonomy The taxonomy to get the primary term from.
* @param bool $post_id The post ID to check.
*
* @return array|bool|\WP_Error|\WP_Term|null
*/
function get_primary_term( $taxonomy = 'category', $post_id = false ) {
// Bail if no taxonomy.
if ( ! $taxonomy ) {
return false;
}
// If no post ID, set it.
if ( ! $post_id ) {
$post_id = get_the_ID();
}
// If checking for WPSEO.
if ( class_exists( 'WPSEO_Primary_Term' ) ) {
// Get the primary term.
$wpseo_primary_term = new WPSEO_Primary_Term( $taxonomy, $post_id );
$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
// If we have one, return it.
if ( $wpseo_primary_term ) {
return get_term( $wpseo_primary_term );
}
}
// We don't have a primary, so let's get all the terms.
$terms = get_the_terms( $post_id, $taxonomy );
// Bail if no terms.
if ( ! $terms || is_wp_error( $terms ) ) {
return false;
}
// Return the first term.
return $terms[0];
}
/**
* Get image placeholder svg...
*
* @return string
*/
function get_placeholder() {
return "data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%203%203'%3E%3C/svg%3E";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment