Last active
November 19, 2022 16:16
-
-
Save agustinprosperi/6740a3f4ba72b076bd78fca9f4dff525 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Funciones utiles | |
*/ | |
if (!defined('ABSPATH')) { | |
exit('No direct access allowed'); | |
} | |
if (!defined('TT_SESSION_TRANSIENT_KEY')) { | |
$cookie_key = 'tt_sesiones_' . COOKIEHASH; | |
$session_transient_key = !empty($_COOKIE[$cookie_key]) ? $_COOKIE[$cookie_key] : ''; | |
if (empty($session_transient_key)) { | |
$session_transient_key = 'tt_sesiones_' . md5(uniqid('', true) . time()); | |
setcookie($cookie_key, $session_transient_key, 0, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true); | |
} | |
define('TT_SESSION_TRANSIENT_KEY', $session_transient_key); | |
} | |
/** | |
* Mostrar notificaciones en el backend | |
* @return html|void | |
*/ | |
add_action('admin_notices', 'tt_admin_notices', 100); | |
function tt_admin_notices() { | |
$admin_notices = tt_get_cookie_session_value('admin_notices', array()); | |
if (empty($admin_notices)) { | |
return; | |
} | |
$notices = array('updated' => 'notice-success', 'message' => 'notice-info', 'error' => 'notice-error', 'warning' => 'notice-warning'); | |
foreach ($admin_notices as $type => $messages) { | |
echo '<div class="notice ' . $notices[$type] . ' is-dismissible">'; | |
foreach ((array) $messages as $text) { | |
printf('<p> %s </p>', $text); | |
} | |
echo '<button type="button" class="notice-dismiss"><span class="screen-reader-text">Descartar este aviso.</span></button></div>'; | |
} | |
tt_add_cookie_session_value('admin_notices', array()); | |
} | |
/** | |
* Guardar en sessiones notificacines para el backend | |
* @param string $text | |
* @param string $type | |
*/ | |
function tt_add_admin_notices($text, $type = 'update') { | |
if (empty($text)) { | |
return; | |
} | |
if (!in_array($type, array('updated', 'error', 'message', 'warning'))) { | |
$type = 'updated'; | |
} | |
$admin_notices = tt_get_cookie_session_value('admin_notices', array()); | |
$admin_notices[$type][] = $text; | |
tt_add_cookie_session_value('admin_notices', $admin_notices); | |
} | |
// Alias | |
function add_flash_admin_notices($text, $type = 'update') { | |
tt_add_admin_notices($text, $type); | |
} | |
/** | |
* Agregar valores a una cookie, pare reemplazar las sesiones | |
*/ | |
function tt_add_cookie_session_value($key, $value) { | |
$tt_sesiones = wp_cache_get(TT_SESSION_TRANSIENT_KEY); | |
if ($tt_sesiones === false) { | |
$tt_sesiones = array(); | |
} | |
$tt_sesiones[$key] = $value; | |
set_transient(TT_SESSION_TRANSIENT_KEY, $tt_sesiones, DAY_IN_SECONDS); | |
wp_cache_set(TT_SESSION_TRANSIENT_KEY, $tt_sesiones); | |
} | |
// | |
function tt_get_cookie_session_value($key, $default = false) { | |
$tt_sesiones = wp_cache_get(TT_SESSION_TRANSIENT_KEY); | |
if ($tt_sesiones === false) { | |
$tt_sesiones = get_transient(TT_SESSION_TRANSIENT_KEY); | |
if (!empty($tt_sesiones)) { | |
wp_cache_add(TT_SESSION_TRANSIENT_KEY, $tt_sesiones); | |
} | |
} | |
return isset($tt_sesiones[$key]) ? $tt_sesiones[$key] : $default; | |
} | |
/** | |
* Agregar mensaje de notificacion que se guarda en session y se muestra una sola vez en el back o front | |
* @param string $text Texto de mensaje | |
* @param string $type Tipo de mensaje 'update', 'updated', 'error', 'message' | |
* @param string $context Opcional contexto que se puede usar para mostrar mensajes en diferentes posiciones de una pagina | |
* @return void | |
*/ | |
function add_flash_messages($text, $type, $context = 'default') { | |
if (empty($text)) return; | |
$type = in_array($type, array('update', 'updated', 'error', 'message')) ? $type : 'update'; | |
$context = !empty($context) ? $context : 'default'; | |
$flash_messages = tt_get_cookie_session_value('flash_messages', array()); | |
$flash_messages[$context][$type][] = $text; | |
tt_add_cookie_session_value('flash_messages', $flash_messages); | |
} | |
/** | |
* Mostrar notificaciones html en formato de backend WP notices | |
* @param string $context Opcional | |
* @return print html | |
*/ | |
function print_flash_messages($context = 'default') { | |
$flash_messages = tt_get_cookie_session_value('flash_messages', array()); | |
if (!isset($flash_messages[$context])) return; | |
$notices = array('updated' => 'notice-success', 'message' => 'notice-success', 'error' => 'notice-error'); | |
foreach ((array)$flash_messages[$context] as $type => $messages) { | |
echo '<div class="notice ' . $notices[$type] . ' is-dismissible">'; | |
foreach ((array)$messages as $text) | |
printf('<p> %s </p>', ($text)); | |
echo '<button type="button" class="notice-dismiss"><span class="screen-reader-text">Descartar este aviso.</span></button></div>'; | |
} | |
unset($flash_messages[$context]); | |
tt_add_cookie_session_value('flash_messages', $flash_messages); | |
} | |
/** | |
* Mostrar notificaciones html en formato de frontend | |
* @param string $context Opcional | |
* @return print html | |
*/ | |
function print_flash_messages_front($context = 'default') { | |
$flash_messages = tt_get_cookie_session_value('flash_messages', array()); | |
if (!isset($flash_messages[$context])) return; | |
$clases = array( | |
'update' => 'success', | |
'updated' => 'success', | |
'error' => 'danger', | |
'message' => 'info' | |
); | |
foreach ((array)$flash_messages[$context] as $type => $messages) { | |
echo '<div class="alert alert-' . $clases[$type] . ' alert-dismissible fade show" role="alert">'; | |
echo implode('<br>', (array)$messages); | |
echo '<span class="btn-close" data-bs-dismiss="alert" aria-label="Close"></span></div>'; | |
} | |
unset($flash_messages[$context]); | |
tt_add_cookie_session_value('flash_messages', $flash_messages); | |
} | |
/** | |
* Devuelve la url actual con parametros url | |
* @return url | |
*/ | |
function tt_current_url() { | |
$server = $_SERVER; | |
//Figure out whether we are using http or https. | |
$http = 'http'; | |
//If HTTPS is present in our $_SERVER array, the URL should | |
//start with https:// instead of http:// | |
if (isset($server['HTTPS'])) { | |
$http = 'https'; | |
} | |
//Get the HTTP_HOST. | |
$host = $server['HTTP_HOST']; | |
//Get the REQUEST_URI. i.e. The Uniform Resource Identifier. | |
$requestUri = $server['REQUEST_URI']; | |
//Finally, construct the full URL. | |
//Use the function htmlentities to prevent XSS attacks. | |
// return $http . '://' . htmlentities($host) . '/' . htmlentities($requestUri); | |
return $http . '://' . htmlentities($host) . ($requestUri); | |
} | |
/** | |
* Devuelve el ID de post de un atachment segun la url | |
* @param string $url | |
* @return int | |
*/ | |
function get_attachment_id_by_url($url) { | |
/* | |
* As get_attachment_by_url won't work on resized versions of images, | |
* we strip out the size part of an image URL. | |
*/ | |
$url = preg_replace('/(.*)-\d+x\d+\.(jpg|png|gif)$/', '$1.$2', $url); | |
// Don't try to do this for external URLs. | |
if (strpos($url, get_site_url()) !== 0) { | |
return 0; | |
} | |
global $wpdb; | |
$id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $url)); | |
return $id ? $id : 0; | |
} | |
/** | |
* Devuelve titulo de un atachment segun la url | |
* @param string $url | |
* @return string|null | |
*/ | |
function get_attachment_alt_name_by_url($url) { | |
if ($attachment_id = get_attachment_id_by_url($url)) { | |
$urlPost = get_post($attachment_id); | |
if ($alt = get_post_meta($urlPost->ID, '_wp_attachment_image_alt', true)) { | |
return $alt; | |
} | |
return $urlPost->post_title; | |
} else { | |
$path_parts = pathinfo($url); | |
return isset($path_parts['filename']) ? $path_parts['filename'] : basename($url); | |
} | |
} | |
/** | |
* Devuelve la ruta de una url | |
* @param string $url | |
* @return string | |
*/ | |
function get_path_from_url($url) { | |
if (!function_exists("get_home_path")) { | |
require_once ABSPATH . '/wp-admin/includes/file.php'; | |
} | |
return str_replace(trailingslashit(site_url()), trailingslashit(get_home_path()), $url); | |
} | |
/** | |
* Devuelve el texto alt o titulo | |
* @param int $id | |
* @return string | |
*/ | |
function get_attachment_alt_name_by_id($id) { | |
$image_alt = get_post_meta($id, '_wp_attachment_image_alt', true); | |
if (empty($image_alt)) { | |
$image_alt = get_the_title($id); | |
} | |
return $image_alt; | |
} | |
/** | |
* Muestra el atributo de enlace target _blank si el parametro dado no esta vacio | |
* @param bool $blank | |
* @return string | |
*/ | |
function tt_link_blank($blank, $echo = true) { | |
if (!empty($blank)) { | |
if ($echo) { | |
echo ' target="_blank" rel="nofollow noopener" '; | |
} else { | |
return ' target="_blank" rel="nofollow noopener" '; | |
} | |
} | |
} | |
/** | |
* Funcion para reemplazar el xdebug dando estilos la etiqueta pre y envolviendo en etiquetas pre el var_dump si es que xdebug no esta instalado | |
* @param mixed $x Cualquier parametro que se quiera pasar a la funcion var_dump | |
* @return string | |
*/ | |
function var_dump_x($x = '') { | |
echo '<style type="text/css">.xdebug-var-dump{ | |
line-height: 1.05; | |
white-space: pre-wrap; | |
white-space: -moz-pre-wrap; | |
white-space: -pre-wrap; | |
white-space: -o-pre-wrap; | |
word-wrap: break-word; | |
word-break: break-word; | |
margin: 5px 0px; | |
padding: 5px; | |
font-size: 14px; | |
-webkit-hyphens: auto; | |
-moz-hyphens: auto; | |
-ms-hyphens: auto; | |
hyphens: auto; | |
}</style>'; | |
if (function_exists("xdebug_get_code_coverage")) { | |
var_dump($x); | |
} else { | |
echo '<pre class="xdebug-var-dump" dir="ltr">'; | |
var_dump($x); | |
echo '</pre>'; | |
} | |
} | |
/** | |
* Funcion para reemplazar el xdebug dando estilos la etiqueta pre y envolviendo en etiquetas pre el var_export si es que xdebug no esta instalado | |
* @param mixed $x Cualquier parametro que se quiera pasar a la funcion var_export | |
* @return string | |
*/ | |
function var_export_x($x = '') { | |
echo '<style type="text/css">.xdebug-var-dump{ | |
line-height: 1.05; | |
white-space: pre-wrap; | |
white-space: -moz-pre-wrap; | |
white-space: -pre-wrap; | |
white-space: -o-pre-wrap; | |
word-wrap: break-word; | |
word-break: break-word; | |
margin: 5px 0px; | |
padding: 5px; | |
font-size: 14px; | |
-webkit-hyphens: auto; | |
-moz-hyphens: auto; | |
-ms-hyphens: auto; | |
hyphens: auto; | |
}</style>'; | |
echo '<pre class="xdebug-var-dump" dir="ltr">'; | |
var_export($x); | |
echo '</pre>'; | |
} | |
/** | |
* Devuelve la ip del cliente solo si se encuentra en la global $_SERVER | |
* @return string | |
*/ | |
function tt_get_client_ip_address() { | |
$ipaddress = ''; | |
if (!empty($_SERVER['HTTP_CLIENT_IP'])) { | |
$ipaddress = $_SERVER['HTTP_CLIENT_IP']; | |
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { | |
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; | |
} else if (!empty($_SERVER['HTTP_X_FORWARDED'])) { | |
$ipaddress = $_SERVER['HTTP_X_FORWARDED']; | |
} else if (!empty($_SERVER['HTTP_FORWARDED_FOR'])) { | |
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR']; | |
} else if (!empty($_SERVER['HTTP_FORWARDED'])) { | |
$ipaddress = $_SERVER['HTTP_FORWARDED']; | |
} else if (!empty($_SERVER['REMOTE_ADDR'])) { | |
$ipaddress = $_SERVER['REMOTE_ADDR']; | |
} else { | |
$ipaddress = 'UNKNOWN'; | |
} | |
// Filtrar la primera direccion IP si vienen mas de una | |
foreach (explode(',', $ipaddress) as $ip) { | |
$ip = trim($ip); | |
if (filter_var($ip, FILTER_VALIDATE_IP)) { | |
return $ip; | |
} | |
} | |
return $ipaddress; | |
} | |
/** | |
* Devuelve la variable despues de comprobar si no es empty | |
* @param mixed $var | |
* @param mixed $default Opcional valor por defecto en caso de que $var sea empty | |
* @return mixed | |
*/ | |
function tt_if_not_empty($var, $default = null) { | |
return (empty($var) && !is_scalar($var) || (is_scalar($var) && $var == '')) ? $default : $var; | |
} | |
/** | |
* Recibe una url y la devuelve sin http/https | |
* @param string $url | |
* @return string | |
*/ | |
function tt_url_sin_http($url) { | |
$find = array('http://', 'https://'); | |
return str_replace($find, '', $url); | |
} | |
/** | |
* Obtener el termino principal de una taxonomia asignado a un post, si no existe un principal se devuelve el primero encontrado | |
* @param int $post_id | |
* @param string $taxonomy | |
* @return WP_Term|false | |
*/ | |
function tt_term_principal($post_id, $taxonomy = 'category') { | |
// Primero buscar en el meta de post | |
if ($meta = get_post_meta($post_id, '_yoast_wpseo_primary_' . $taxonomy, true)) { | |
$term = get_term($meta, $taxonomy); | |
if (!is_wp_error($term) && $term) { | |
return $term; | |
} | |
} | |
// Segundo el primero de la taxonomia | |
$terms = get_the_terms($post_id, $taxonomy); | |
if (!is_wp_error($terms) && $terms) { | |
return $terms[0]; | |
} | |
return false; | |
} | |
/** | |
* Devuleve el valor de un elemento de array/objeto si existe el index/prop | |
* @param mixed $mixed | |
* @param string $index | |
* @param mixed $default | |
* @return mixed | |
*/ | |
function value_if_index_exists($mixed, $index, $default = '') { | |
if (is_object($mixed)) { | |
return isset($mixed->$index) ? $mixed->$index : $default; | |
} elseif (is_array($mixed)) { | |
return isset($mixed[$index]) ? $mixed[$index] : $default; | |
} | |
return $default; | |
} | |
/** | |
* Limpia todos los caracteres que no sean numero de un string | |
* @param string $str | |
* @return string El string con solo numeros | |
*/ | |
function tt_clean_but_numbers($str) { | |
return preg_replace('/[^0-9]/', '', $str); | |
} | |
/** | |
* Devuelve un array con todos los metas de un post, despues de haber aplicado la funcion maybe_unserialize a todos los metas | |
* @param int $post_ID ID del post | |
* @return array Array con todos los metas | |
*/ | |
function tt_get_post_metas($post_ID) { | |
$pmdata = get_post_meta($post_ID); | |
if (!empty($pmdata)) { | |
return array_map(function ($v) { | |
return maybe_unserialize($v[0]); | |
}, $pmdata); | |
} | |
return false; | |
} | |
/** | |
* Obtener post_meta o un valor por default | |
*/ | |
function tt_get_post_meta($post_id, $meta_key, $default = false) { | |
$value = get_post_meta($post_id, $meta_key, true); | |
return tt_if_not_empty($value, $default); | |
} | |
/** | |
* Valida una fecha pasada en string, con el parametro opcional de formato | |
* @param string $date | |
* @param string $format | |
* @return bool | |
*/ | |
function tt_validar_fecha($date, $format = 'Y-m-d H:i:s', $timezone = null) { | |
$d = DateTime::createFromFormat($format, $date, $timezone); | |
return $d && $d->format($format) == $date; | |
} | |
/** | |
* Reemplazar el directorio de subida momentaneamente | |
* @param string $carpeta | |
*/ | |
function tt_cambiar_upload_dir($carpeta) { | |
add_filter('upload_dir', function ($dir) use ($carpeta) { | |
return array( | |
'path' => $dir['basedir'] . '/' . $carpeta, | |
'url' => $dir['baseurl'] . '/' . $carpeta, | |
'subdir' => '/' . $carpeta, | |
) + $dir; | |
}); | |
} | |
/** | |
* Actualizar directamente en base de datos un post | |
* @param array $args El ID $args['ID'] es obligatorio para poder hacer la actualizacion | |
* @return bool | |
*/ | |
function tt_actualizar_post_db($args) { | |
global $wpdb; | |
if (empty($args['ID'])) { | |
return false; | |
} | |
$post_id = $args['ID']; | |
unset($args['ID']); | |
return $wpdb->update($wpdb->posts, $args, array('ID' => $post_id)); | |
} | |
/** | |
* Guardar log custom en el archivo debug.log | |
* @param string $logtext | |
* @param mixed $extra Opcional | |
*/ | |
function tt_debug_log($logtext, $extra = '') { | |
$date = date("d-M-Y H:i:s"); | |
// Logar el archivo y la linea del codigo | |
if (function_exists('debug_backtrace')) { | |
$bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1); | |
$caller = array_shift($bt); | |
$implode = array( | |
'file:' . basename($caller['file']), | |
'line:' . $caller['line'], | |
); | |
$logtext .= ' | ' . implode(' ', $implode); | |
} | |
$logtext .= ' | Current-url:' . tt_current_url(); | |
if (!empty($extra)) { | |
$logtext .= ' | Extra-Data: ' . print_r($extra, true); | |
} | |
$logtext = sprintf("[%s] %s" . PHP_EOL, $date, $logtext); | |
$file = WP_CONTENT_DIR . '/debug.log'; | |
@file_put_contents($file, $logtext, FILE_APPEND | LOCK_EX); | |
} | |
/** | |
* FUNCION AJUSTAR IMAGENES SIN DEFORMAR ANCHO Y ALTO CONCRETO | |
* Nombre de funcion original wpse128538_resize | |
* @param string $url | |
* @param int $width | |
* @param int $height | |
* @param bool $crop | |
* @param bool $single | |
* @return string|array|false URL de nueva imagen o un array con url, with y height, depende de $single, o false | |
*/ | |
function tt_resize_img_from_url($url, $width, $height = null, $crop = false, $single = true) { | |
//validate inputs | |
if (!$url or !$width) { | |
return false; | |
} | |
//define upload path & dir | |
$upload_info = wp_upload_dir(); | |
$upload_dir = $upload_info['basedir']; | |
$upload_url = $upload_info['baseurl']; | |
//check if $img_url is local | |
if (strpos($url, $upload_url) === false) { | |
return false; | |
} | |
//define path of image | |
$rel_path = str_replace($upload_url, '', $url); | |
$img_path = $upload_dir . $rel_path; | |
//check if img path exists, and is an image indeed | |
if (!file_exists($img_path) or !getimagesize($img_path)) { | |
return false; | |
} | |
//get image info | |
$info = pathinfo($img_path); | |
$ext = $info['extension']; | |
list($orig_w, $orig_h) = getimagesize($img_path); | |
//get image size after cropping | |
$dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); | |
$dst_w = $dims[4]; | |
$dst_h = $dims[5]; | |
//use this to check if cropped image already exists, so we can return that instead | |
$suffix = "{$dst_w}x{$dst_h}"; | |
$dst_rel_path = str_replace('.' . $ext, '', $rel_path); | |
$destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}"; | |
if (!$dst_h) { | |
//can't resize, so return original url | |
$img_url = $url; | |
$dst_w = $orig_w; | |
$dst_h = $orig_h; | |
} elseif (file_exists($destfilename) && getimagesize($destfilename)) { | |
//else check if cache exists | |
$img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; | |
} else { | |
//else, we resize the image and return the new resized image url | |
// Note: pre-3.5 fallback check | |
if (function_exists('wp_get_image_editor')) { | |
$editor = wp_get_image_editor($img_path); | |
if (is_wp_error($editor) || is_wp_error($editor->resize($width, $height, $crop))) { | |
return false; | |
} | |
$resized_file = $editor->save(); | |
if (!is_wp_error($resized_file)) { | |
$resized_rel_path = str_replace($upload_dir, '', $resized_file['path']); | |
$img_url = $upload_url . $resized_rel_path; | |
} else { | |
return false; | |
} | |
} else { | |
$resized_img_path = image_resize($img_path, $width, $height, $crop); | |
if (!is_wp_error($resized_img_path)) { | |
$resized_rel_path = str_replace($upload_dir, '', $resized_img_path); | |
$img_url = $upload_url . $resized_rel_path; | |
} else { | |
return false; | |
} | |
} | |
} | |
//return the output | |
if ($single) { | |
//str return | |
$image = $img_url; | |
} else { | |
//array return | |
$image = array( | |
0 => $img_url, | |
1 => $dst_w, | |
2 => $dst_h, | |
); | |
} | |
return $image; | |
} | |
/** | |
* Traer los relacionados de un post por categoria, etiqueta y posts generales | |
* @param int $postID Opcional | |
* @param int $ppp Opcional | |
* @param string $post_type Opcional | |
* @param array $taxonomies Opcional por defecto 'category', 'post_tag' | |
* @return WP_Query | |
*/ | |
function tt_post_relacionados($postID = '', $ppp = 5, $post_type = 'post', $taxonomies = array('category', 'post_tag')) { | |
$postID = (!empty($postID)) ? $postID : get_the_ID(); | |
$exclude_ids = array($postID); | |
// Taxonomies | |
$query = new stdClass(); | |
$query->posts = array(); | |
$query->post_count = 0; | |
while (count($taxonomies) && $query->post_count < $ppp) { | |
$taxonomy = array_shift($taxonomies); | |
$taxonomy__in = array(0); | |
$terms = get_the_terms($postID, $taxonomy); | |
if (!is_wp_error($terms) && is_array($terms)) { | |
$exclude_ids = array_merge($exclude_ids, wp_list_pluck($query->posts, 'ID')); | |
$taxonomy__in = wp_list_pluck($terms, 'term_id'); | |
$query2 = new WP_Query(array( | |
'post_type' => $post_type, | |
'tax_query' => array(array('taxonomy' => $taxonomy, 'field' => 'term_id', 'terms' => $taxonomy__in)), | |
'posts_per_page' => $ppp, | |
'post__not_in' => $exclude_ids, | |
)); | |
if ($query2->post_count) { | |
$query2->posts = array_merge($query->posts, $query2->posts); | |
$query2->post_count = count($query2->posts); | |
$query = $query2; | |
} | |
} | |
} | |
// Todos los posts | |
if ($query->post_count < $ppp) { | |
$exclude_ids = array_merge($exclude_ids, wp_list_pluck($query->posts, 'ID')); | |
$rest = $ppp - $query->post_count; | |
$query2 = new WP_Query(array( | |
'post_type' => $post_type, | |
'posts_per_page' => $rest, | |
'post__not_in' => $exclude_ids, | |
)); | |
if ($query2->post_count) { | |
$query2->posts = array_merge($query->posts, $query2->posts); | |
$query2->post_count = count($query2->posts); | |
$query = $query2; | |
} | |
} | |
return $query; | |
} | |
/** | |
* Incrustar svg en html | |
*/ | |
function tt_html_svg($path, $wrap = '<figure>%s</figure>', $echo = true) { | |
if (empty($wrap)) { | |
$wrap = '%s'; | |
} | |
if ($echo) { | |
printf($wrap, @file_get_contents($path)); | |
} else { | |
return sprintf($wrap, @file_get_contents($path)); | |
} | |
} | |
/** | |
* Imprimir o devolver enlace CTA | |
*/ | |
function tt_acf_cta_link($acf_cta, $classes = '', $echo = true) { | |
if (!empty($acf_cta['url']) && !empty($acf_cta['title'])) { | |
$target = ''; | |
if ($acf_cta['target'] == '_blank') { | |
$target = ' target="_blank" rel="noopener noreferrer" '; | |
} | |
$link = sprintf( | |
'<a class="%s" href="%s" %s>%s</a>', | |
esc_attr($classes), | |
esc_url($acf_cta['url']), | |
$target, | |
esc_html($acf_cta['title']) | |
); | |
if ($echo) { | |
echo $link; | |
} else { | |
return $link; | |
} | |
} | |
} | |
function tt_acf_cta_link_icon($acf_cta, $classes = '', $echo = true) { | |
if (!empty($acf_cta['url']) && !empty($acf_cta['title'])) { | |
$target = ''; | |
if ($acf_cta['target'] == '_blank') { | |
$target = ' target="_blank" rel="noopener noreferrer" '; | |
} | |
$link = sprintf( | |
'<a class="%s" href="%s" %s><img src="%s" alt="%s"/></a>', | |
esc_attr($classes), | |
esc_url($acf_cta['url']), | |
$target, | |
esc_html($acf_cta['icon']), | |
esc_html($acf_cta['title']) | |
); | |
if ($echo) { | |
echo $link; | |
} else { | |
return $link; | |
} | |
} | |
} | |
/** | |
* Obtener los estados para hacer consultas publicas | |
*/ | |
function tt_get_front_statuses() { | |
$statuses = array('publish'); | |
if (is_user_logged_in()) { | |
$statuses[] = 'private'; | |
} | |
return $statuses; | |
} | |
/** | |
* Imprimir img tag para una url | |
* @param url|int $image | |
* @param string|array $attr Se puede usar width|height pero es posible que no se apliquen si $try_attachment es true | |
* @return html | |
*/ | |
function tt_tag_img_from_url($image, $size = 'full', $attr = [], $print = true, $try_attachment = true) { | |
$html = ''; | |
if (empty($image)) { | |
return ''; | |
} | |
$size = empty($size) ? 'full' : $size; | |
// Si se recibe id de adjunto | |
if (is_numeric($image)) { | |
$image_id = $image; | |
$image = wp_get_attachment_image_src($image, $size, false); | |
if (!$image) { | |
return ''; | |
} | |
list($src, $width, $height) = $image; | |
} else { | |
$src = $image; | |
} | |
// Si debemos probar primero con impirmir una imagen adjunta | |
if ($try_attachment) { | |
$image_id = empty($image_id) ? get_attachment_id_by_url($image) : $image_id; | |
$attr_2 = $attr; | |
unset($attr_2['width']); | |
unset($attr_2['height']); | |
$html = wp_get_attachment_image($image_id, $size, '', $attr_2); | |
} | |
// Si no es adjunto se crea el tag img para una url dada | |
if (empty($html)) { | |
$src_file = get_path_from_url($src); | |
if (@file_exists($src_file)) { | |
if (!is_array($image)) { | |
list($width, $height) = @getimagesize($src_file); | |
} | |
$default_attr = array( | |
'src' => $src, | |
'class' => "", | |
'alt' => get_attachment_alt_name_by_url($src), | |
); | |
// Add `loading` attribute. | |
if (wp_lazy_loading_enabled('img', 'wp_get_attachment_image')) { | |
$default_attr['loading'] = 'lazy'; | |
} | |
$attr = wp_parse_args($attr, $default_attr); | |
$attr = array_map('esc_attr', $attr); | |
// Si se va a reemplazar el width y height | |
if (isset($attr['width'])) { | |
$width = $attr['width']; | |
} | |
if (isset($attr['height'])) { | |
$height = $attr['height']; | |
} | |
unset($attr['width']); | |
unset($attr['height']); | |
// | |
$hwstring = image_hwstring($width, $height); | |
$html = rtrim("<img $hwstring"); | |
foreach ($attr as $name => $value) { | |
$html .= " $name=" . '"' . $value . '"'; | |
} | |
$html .= ' />'; | |
} | |
} | |
if ($print) { | |
echo $html; | |
} else { | |
return $html; | |
} | |
} | |
/** | |
* Obtener el tamaño de un svg apartir de a url | |
* @param url|int $image | |
* @return array | |
*/ | |
function tt_sizes_svg_from_url($image) { | |
$svgfile = simplexml_load_file(get_path_from_url($image)); | |
$size = array(); | |
if (!empty($svgfile)) { | |
$attr = $svgfile->attributes(); | |
} | |
if (!empty($attr)) { | |
$size['width'] = floatval($attr->width); | |
$size['height'] = floatval($attr->height); | |
} | |
return $size; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment