Los 26 fragmentos de WordPress más útiles y funcionales
WordPress mejora con los complementos, ya que le permiten personalizar completamente su sitio web para satisfacer sus necesidades. Sin embargo, muchas funciones también se pueden integrar sin utilizar un complemento. Un simple fragmento funciona. Sin embargo, recopilar todos los fragmentos necesarios puede ser bastante tedioso. Por lo tanto, hoy, abriré mi caja de herramientas y enumeraré mis fragmentos favoritos de WordPress.
Compatibilidad:
- Versión de WordPress desde 4.6
- PHP-Versión 7.xx
Copie los fragmentos en la carpeta de su tema activo. functions.php
o configure un complemento personalizado específico de la página para este trabajo.
Recuerde: antes de aplicar cualquier cambio al functions.php, cree una copia de seguridad del archivo. No modifique el archivo con el editor de WordPress. Si algo sale mal, no tendrá acceso a su sitio web. Haga sus adiciones usando un acceso FTP, directamente en su espacio web.
WordPress Tag Cloud es una herramienta popular para la barra lateral de un blog. Sus visitantes pueden usarlo para encontrar fácilmente lo que buscan. Sin embargo, WordPress muestra las etiquetas en diferentes tamaños, lo que no siempre es algo deseado. Utilice este fragmento para eliminar los estilos en línea.
<?php
/**
* Remove style from Tag Clouds
* @author Andreas Hecht
*/
function drweb_remove_tagcloud_inline_style($input){
return preg_replace('/ style=("|')(.*?)("|')/','',$input);
}
add_filter('wp_generate_tag_cloud', 'drweb_remove_tagcloud_inline_style',10,1);
2 – Apague sus Pingbacks de autorreferencia
Los pingbacks y trackbacks generalmente no son malos. Le informan si sus artículos se mencionaron o se vincularon en otros sitios web. Lamentablemente, WordPress tiene la mala costumbre de informarle sobre los enlaces de sus artículos en su propio sitio web. Este fragmento te permite desactivar estos molestos mensajes.
<?php
/**
* Disable self pingbacks
*
*/
function evolution_no_self_ping( &$links ) {
$home = get_option( 'home' );
foreach ( $links as $l => $link )
if ( 0 === strpos( $link, $home ) )
unset($links[$l]);
}
add_action( 'pre_ping', 'evolution_no_self_ping' );
3 – Desactive los emojis de WordPress
No todo el mundo es fanático de los coloridos emojis. Si no desea utilizar emojis en sus publicaciones, puede desactivar esta función. El rendimiento de tu blog te lo agradecerá.
<?php
/**
* Disable the emojis
*/
function disable_emojis() {
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
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( 'tiny_mce_plugins', 'disable_emojis_tinymce' );
add_filter( 'wp_resource_hints', 'disable_emojis_remove_dns_prefetch', 10, 2 );
}
add_action( 'init', 'disable_emojis' );
/**
* Filter function used to remove the tinymce emoji plugin.
*
* @param array $plugins
* @return array Difference betwen the two arrays
*/
function disable_emojis_tinymce( $plugins ) {
if ( is_array( $plugins ) ) {
return array_diff( $plugins, array( 'wpemoji' ) );
} else {
return array();
}
}
/**
* Remove emoji CDN hostname from DNS prefetching hints.
*
* @param array $urls URLs to print for resource hints.
* @param string $relation_type The relation type the URLs are printed for.
* @return array Difference betwen the two arrays.
*/
function disable_emojis_remove_dns_prefetch( $urls, $relation_type ) {
if ( 'dns-prefetch' == $relation_type ) {
/** This filter is documented in wp-includes/formatting.php */
$emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' );
$urls = array_diff( $urls, array( $emoji_svg_url ) );
}
return $urls;
}
4 – Desactive el script de migración de jQuery
jQuery Migrate es un script destinado a crear una compatibilidad descendente de aplicaciones jQuery más antiguas. La versión «normal» y moderna de jQuery ya no es compatible con todas las aplicaciones antiguas. Si bien esto no afectará a más del 5% de todos los sitios web de WordPress, WordPress carga el script bastante considerable de forma predeterminada. Aquí tienes una forma fácil de apagarlo:
<?php
/**
* Dequeue jQuery Migrate Script in WordPress.
*/
if ( ! function_exists( 'evolution_remove_jquery_migrate' ) ) :
function evolution_remove_jquery_migrate( &$scripts) {
if(!is_admin()) {
$scripts->remove( 'jquery');
$scripts->add( 'jquery', false, array( 'jquery-core' ), '1.12.4' );
}
}
add_filter( 'wp_default_scripts', 'evolution_remove_jquery_migrate' );
endif;
5 – Desactivar la función oEmbed de WordPress
La versión 4.4 de WordPress nos trajo la nueva función oEmbed, que está principalmente destinada a permitirle integrar artículos o páginas extranjeras en sus publicaciones con un simple enlace. Si no necesita esta función, o simplemente no desea que sus artículos se puedan mostrar en publicaciones extranjeras en cualquier momento, simplemente desactive esta función.
<?php
/**
* Disable embeds on init.
*
* - Removes the needed query vars.
* - Disables oEmbed discovery.
* - Completely removes the related JavaScript.
*
* @since 1.0.0
*/
function evolution_disable_embeds_init() {
/* @var WP $wp */
global $wp;
// Remove the embed query var.
$wp->public_query_vars = array_diff( $wp->public_query_vars, array(
'embed',
) );
// Remove the REST API endpoint.
remove_action( 'rest_api_init', 'wp_oembed_register_route' );
// Turn off oEmbed auto discovery.
add_filter( 'embed_oembed_discover', '__return_false' );
// Don't filter oEmbed results.
remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
// Remove oEmbed discovery links.
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
// Remove oEmbed-specific JavaScript from the front-end and back-end.
remove_action( 'wp_head', 'wp_oembed_add_host_js' );
add_filter( 'tiny_mce_plugins', 'evolution_disable_embeds_tiny_mce_plugin' );
// Remove all embeds rewrite rules.
add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
// Remove filter of the oEmbed result before any HTTP requests are made.
remove_filter( 'pre_oembed_result', 'wp_filter_pre_oembed_result', 10 );
}
add_action( 'init', 'evolution_disable_embeds_init', 9999 );
/**
* Removes the 'wpembed' TinyMCE plugin.
*
* @since 1.0.0
*
* @param array $plugins List of TinyMCE plugins.
* @return array The modified list.
*/
function evolution_disable_embeds_tiny_mce_plugin( $plugins ) {
return array_diff( $plugins, array( 'wpembed' ) );
}
/**
* Remove all rewrite rules related to embeds.
*
* @since 1.0.0
*
* @param array $rules WordPress rewrite rules.
* @return array Rewrite rules without embeds rules.
*/
function evolution_disable_embeds_rewrites( $rules ) {
foreach ( $rules as $rule => $rewrite ) {
if ( false !== strpos( $rewrite, 'embed=true' ) ) {
unset( $rules[ $rule ] );
}
}
return $rules;
}
/**
* Remove embeds rewrite rules on plugin activation.
*
* @since 1.0.0
*/
function evolution_disable_embeds_remove_rewrite_rules() {
add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
flush_rewrite_rules( false );
}
register_activation_hook( __FILE__, 'evolution_disable_embeds_remove_rewrite_rules' );
/**
* Flush rewrite rules on plugin deactivation.
*
* @since 1.0.0
*/
function evolution_disable_embeds_flush_rewrite_rules() {
remove_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
flush_rewrite_rules( false );
}
register_deactivation_hook( __FILE__, 'evolution_disable_embeds_flush_rewrite_rules' );
6 – Libera el encabezado de WordPress de entradas innecesarias
WordPress carga un montón de cosas a través del wp_head()
enganche en el encabezado de los temas de WordPress. Algunos de ellos son muy útiles, otros no. Algunos simplemente inflan el sitio web innecesariamente. Aquí hay un pequeño fragmento para hacer una limpieza importante.
<?php
/**
* Frees the header from unnecessary entries
*/
add_action('init', 'evolution_remheadlink');
function evolution_remheadlink()
{
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'parent_post_rel_link', 10, 0);
remove_action('wp_head', 'start_post_rel_link', 10, 0);
remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
remove_action('wp_head', 'wp_shortlink_header', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
}
7 – Inyectar imágenes de publicaciones en la fuente RSS
De forma predeterminada, WordPress no agrega imágenes de publicaciones a la fuente RSS. Este fragmento cambia eso.
<?php
/**
* Add Post Images to the RSS Feed
*/
function evolution_featuredtoRSS($content) {
global $post;
if ( has_post_thumbnail( $post->ID ) ){
$content="<div>" . get_the_post_thumbnail( $post->ID, 'large', array( 'style' => 'margin-bottom: 15px;' ) ) . '</div>' . $content;
}
return $content;
}
add_filter('the_excerpt_rss', 'evolution_featuredtoRSS');
add_filter('the_content_feed', 'evolution_featuredtoRSS');
8 – Permitir formatos de archivo adicionales para la biblioteca de medios
¿Desea cargar formatos de archivo especiales en su biblioteca de medios de WordPress y recibe un mensaje de error? Utilice este código y su problema estará resuelto. El código le permite cargar los formatos de archivo. ZIP
, MOBI
, PDF
, y EPUB
. Si necesita más formatos, busque el lista completa de tipos MIME aquí.
<?php
/**
* Add further Mime types for the download of the products
*/
function add_custom_mime_types($mimes){
$new_file_types = array (
'zip' => 'application/zip',
'mobi' => 'application/x-mobipocket-ebook',
'pdf' => 'application/pdf',
'epub' => 'application/epub+zip'
);
return array_merge($mimes,$new_file_types);
}
add_filter('upload_mimes','add_custom_mime_types');
9 – Defina libremente la longitud del extracto
A veces, se necesita una longitud de extracto muy precisa para una determinada plantilla. La siguiente función le permite definir esta longitud libremente. Lo bueno es que la longitud del extracto no se establece globalmente, lo que permite que cada plantilla tenga su propia longitud.
<?php
/**
* Custom Excerpt Lenght
*
*/
the_excerpt_max_charlength(190);
function the_excerpt_max_charlength($charlength) {
$excerpt = get_the_excerpt();
$charlength++;
if ( mb_strlen( $excerpt ) > $charlength ) {
$subex = mb_substr( $excerpt, 0, $charlength - 5 );
$exwords = explode( ' ', $subex );
$excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
if ( $excut < 0 ) {
echo mb_substr( $subex, 0, $excut );
} else {
echo $subex;
}
echo '...';
} else {
echo $excerpt;
}
}
En la plantilla, simplemente intercambie las etiquetas y defina la longitud del extracto:
// Deleting the original tag:
<?php the_excerpt(); ?>
// Exchange with this tag, and enter any length (in brackets):
<?php the_excerpt_max_charlength( 250 ); ?>
10 – Vídeos adaptables – YouTube y Vimeo
Si su tema no admite videos receptivos, la configuración del soporte para hacerlo se puede hacer muy rápidamente. Una función PHP permite una incrustación automática en un Div, mientras que la información CSS asegura que haya una escala óptima en cualquier resolución.
<?php
/**
* Responsive Videos, Youtube and Vimeo
*
*/
function evolution_wrap_oembed( $html ){
$html = preg_replace( '/(width|height)="d*"s/', "", $html ); // Strip width and height #1
return'<div class="embed-responsive embed-responsive-16by9">'.$html.'</div>'; // Wrap in div element and return #3 and #4
}
add_filter( 'embed_oembed_html','evolution_wrap_oembed',10,1);
El CSS necesario:
.embed-responsive.embed-responsive-16by9 {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
padding-top: 25px;
height: 0;
}
.embed-responsive.embed-responsive-16by9 iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
/* This indication makes HTML5 videos responsive */
video {
width: 100% !important;
height: auto !important;
}
11 – Configuración de la paginación de WordPress sin un complemento
¿Desea reemplazar las «publicaciones más antiguas | publicaciones más nuevas ”con una lista interesante de números? No hay problema, ya que con la versión 4.1 de WordPress ya no necesita el popular complemento WP PageNavi. Ahora, hacer esto es muy fácil de hacer usando los medios predeterminados.
Puede utilizar esta función directamente en el index.php
, y en el archive.php
. Sin embargo, creando un tema hijo para hacerlo es ventajoso.
<?php the_posts_pagination( array(
'mid_size' => 3, //How many buttons will be displayed before the placeholder »...« appears.
'type' => 'list', // Display as a list
'prev_text' => __( '« Newer', 'textdomain' ),
'next_text' => __( 'Older »', 'textdomain' ),
) ); ?>
Para darle un diseño a la lista, se necesita algo de CSS. Estos son los estilos que uso de vez en cuando. Necesitas ajustarlo a los colores de tu blog:
nav.pagination{position:relative;display:block;margin-top:20px}
.page-numbers{margin:0;padding:0}
.page-numbers li{list-style:none;margin:0 6px 0 0;padding:0;display:inline-block}
.page-numbers li span.current{padding:10px 15px;background:#9FC65D;border:1px solid #9FC65D;display:block;line-height:1;color:#fff}
.page-numbers li a{padding:10px 15px;background:#eee;color:#555;text-decoration:none;border:1px solid #eee;display:block;line-height:1}
.page-numbers li a:hover{background:#9FC65D;border-color:#9FC65D;color:#fff}
.screen-reader-text {
clip: rect(1px,1px,1px,1px);
position: absolute!important;
height: 1px;
width: 1px;
overflow: hidden;
}
12 – Logotipo de inicio de sesión personalizado con un color de fondo personalizado
¿Está realmente orgulloso de su sitio web WordPress y ha puesto mucho esfuerzo en el diseño? Dé un paso más y ajuste el logotipo en la página de inicio de sesión. En combinación con su propio color de fondo, esto se ve muy bien.
<?php
/**
* A new logo for the admin area and an own background color
* @author Andreas Hecht
*/
function ah_login_logo() {
?>
<style type="text/css">
#login h1 a, .login h1 a {
background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/dein-logo.png);
margin-bottom: 0;
background-size: 180px;
height: 180px;
width: 180px;
margin-left: auto;
margin-right: auto;
border-radius: 50%;
}
body.login {background-color: #0073bf;} .login #backtoblog a, .login #nav a {color: #fff !important}
</style>
<?php }
add_action( 'login_enqueue_scripts', 'ah_login_logo' );
13 – Cambiar el aspecto del primer párrafo
Su artículo solo se verá realmente genial cuando el primer párrafo esté diseñado en un color y fuente diferente. Para hacerlo, ni siquiera necesita cambiar al área de texto de su editor, ya que WordPress mismo puede hacerlo automáticamente. Dos fragmentos hacen el truco:
<?php
/**
* Auto-Highlighting - Automatic highlighting of a post's first paragraph
* @author Andreas Hecht
*/
function tb_first_paragraph_highlight( $content ) {
return preg_replace( '/<p([^>]+)?>/', '<p$1 class="opener">', $content, 1 );
}
add_filter( 'the_content', 'tb_first_paragraph_highlight' );
El código de arriba agrega la clase .opener
al primer párrafo de cada artículo o página. Ahora, un poco de CSS le permite controlar el formato del párrafo, así como el «lugar» de acción.
/* Only selected articles get the design */
.single p.opener {
color: #165a72;
font-weight: 400;
font-size: 21px;
line-height: 1.5;
}
O los artículos y las páginas muestran el primer párrafo de manera diferente:
/* Individual articles and pages are designed */
.single p.opener, .page p.opener {
color: #165a72;
font-weight: 400;
font-size: 21px;
line-height: 1.5;
}
14 – Registro de usuario solo con correo electrónico y contraseña
Desde la versión 4.5 de WordPress, es posible un registro de usuario a través de una dirección de correo electrónico y una contraseña. Para molestar a los piratas informáticos y hacer que WordPress sea un poco más seguro, puede registrarse por correo electrónico y contraseña utilizando exclusivamente este código.
<?php
// Copy from here
//Deleting WordPress authentification
remove_filter('authenticate', 'wp_authenticate_username_password', 20);
// Placing new authentification - sign up via email and password only
add_filter('authenticate', function($user, $email, $password){
//Check for empty fields
if(empty($email) || empty ($password)){
//create new error object and add errors to it.
$error = new WP_Error();
if(empty($email)){ //No email
$error->add('empty_username', __('<strong>ERROR</strong>: Email field is empty.'));
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //Invalid Email
$error->add('invalid_username', __('<strong>ERROR</strong>: Email is invalid.'));
}
if(empty($password)){ //No password
$error->add('empty_password', __('<strong>ERROR</strong>: Password field is empty.'));
}
return $error;
}
//Check if user exists in WordPress database
$user = get_user_by('email', $email);
//bad email
if(!$user){
$error = new WP_Error();
$error->add('invalid', __('<strong>ERROR</strong>: Either the email or password you entered is invalid.'));
return $error;
}
else{ //check password
if(!wp_check_password($password, $user->user_pass, $user->ID)){ //bad password
$error = new WP_Error();
$error->add('invalid', __('<strong>ERROR</strong>: Either the email or password you entered is invalid.'));
return $error;
}else{
return $user; //passed
}
}
}, 20, 3);
15 – Evite que los usuarios cambien sus contraseñas
El área de administración de WordPress es el corazón y los pulmones de su sitio web. Asegúrese de que las contraseñas distribuidas sean muy seguras, sin dar oportunidad a los atacantes. Sin embargo, a los usuarios les gusta cambiar las contraseñas asignadas a versiones muy fáciles de recordar y muy fáciles de piratear. ¡Puedes prevenir eso!
<?php
/**
*
* Preventing users from changing their passwords
*
*/
class Password_Reset_Removed
{
function __construct()
{
add_filter( 'show_password_fields', array( $this, 'disable' ) );
add_filter( 'allow_password_reset', array( $this, 'disable' ) );
}
function disable()
{
if ( is_admin() ) {
$userdata = wp_get_current_user();
$user = new WP_User($userdata->ID);
if ( !empty( $user->roles ) && is_array( $user->roles ) && $user->roles[0] == 'administrator' )
return true;
}
return false;
}
}
$pass_reset_removed = new Password_Reset_Removed();
16 – Visualización de anuncios después del párrafo xx
Si desea ganar dinero con su blog, no podrá utilizar anuncios. Podría utilizar el popular Google Adsense, por ejemplo. Este fragmento muestra sus anuncios después de un párrafo seleccionado.
<?php
/**
* Adding an ad after the second paragraph
*
*/
add_filter( 'the_content', 'tb_insert_post_ads' );
function tb_insert_post_ads( $content ) {
$ad_code="The ad code goes here. Both static ads and Google Adsense.";
if ( is_single() && ! is_admin() ) {
// The number in front of the content defines where the code appears. Here, it pops up after the article's second paragraph.
return tb_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function tb_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
17 – Ampliación de su perfil de usuario con más cuentas de redes sociales
La información biográfica en su perfil de WordPress es bastante escasa. No tiene la opción de vincular todas sus redes sociales. Con este código, puede agregar y mostrar todas sus cuentas de redes sociales.
<?php
/**
* Managing contact fields for author bio
*/
$evolution_pro_Contactfields = new evolution_pro_Contactfields(
// Missing accounts can easily be added
array (
'Feed',
'Twitter',
'Facebook',
'GooglePlus',
'Flickr',
'Xing',
'Github',
'Instagram',
'LinkedIn',
'Pinterest',
'Vimeo',
'Youtube'
)
);
class evolution_pro_Contactfields {
public
$new_fields
, $active_fields
, $replace
;
/**
* @param array $fields New fields: array ('Twitter', 'Facebook')
* @param bool $replace Replace default fields?
*/
public function __construct($fields, $replace = TRUE)
{
foreach ( $fields as $field )
{
$this->new_fields[ mb_strtolower($field, 'utf-8') ] = $field;
}
$this->replace = (bool) $replace;
add_filter('user_contactmethods', array( $this, 'add_fields' ) );
}
/**
* Changing contact fields
* @param $original_fields Original WP fields
* @return array
*/
public function add_fields($original_fields)
{
if ( $this->replace )
{
$this->active_fields = $this->new_fields;
return $this->new_fields;
}
$this->active_fields = array_merge($original_fields, $this->new_fields);
return $this->active_fields;
}
/**
* Helper function
* @return array The currently active fields.
*/
public function get_active_fields()
{
return $this->active_fields;
}
}
Utilice la siguiente etiqueta para mostrar los nuevos campos en el tema:
<?php echo get_the_author_meta( 'facebook' ); ?>
18 – Mostrar una lista de categorías con fuentes RSS
A veces, puede ser útil poder mostrar todas las categorías con sus respectivas direcciones de alimentación RSS. Se vuelve aún mejor cuando puede usar un código corto de WordPress para mostrar la lista en cualquier lugar, incluso en los widgets de texto.
<?php
function tb_categories_with_feed() {
$args = array(
'orderby' => 'name',
'feed' => 'RSS',
'echo' => false,
'title_li' => '',
);
$string .= '<ul>';
$string .= wp_list_categories($args);
$string .= '</ul>';
return $string;
}
// add shortcode
add_shortcode('categories-feed', 'tb_categories_with_feed');
// Add filter to execute shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');
El código corto:
[categories-feed]
te permite mostrar la lista donde quieras. También funciona dentro de los widgets.
También puedes usar el shortcode en tu tema:
<?php echo do_shortcode("[categories-feed]"); ?>
19 – Mostrar publicaciones relacionadas sin un complemento
Las publicaciones similares populares se pueden mostrar fácilmente sin un complemento inflado con «muchas» funciones. Necesita un fragmento de código PHP, un tema hijo y un poco de CSS.
<?php
if ( ! function_exists( 'evolution_related_posts' ) ) :
function evolution_related_posts() {
global $post;
if($post) {
$post_id = get_the_ID();
} else {
$post_id = null;
}
$orig_post = $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 3, // Number of related posts that will be shown.
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div class="related-wrap">';
echo '<h4 class="entry-related">';
_e('Related Posts','evolution');
echo '</h4>';
echo '<div class="related-posts">';
$c = 0; while( $my_query->have_posts() ) {
$my_query->the_post(); $c++;
if( $c == 3) {
$style="third";
$c = 0;
}
else $style=""; ?>
<article class="entry-item <?php echo $style; ?>">
<div class="entry-thumb">
<a href="https://www.noupe.com/wordpress/<?php the_permalink($post->ID); ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail( 'evolution-medium' ); ?></a>
</div>
<div class="content">
<?php if ( ! empty( $categories ) ) {
echo '<span class="cat"><i class="icon-folder-open" aria-hidden="true"></i> <a href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a></span>';
} ?>
<header>
<h4 class="entry-title"><a href="https://www.noupe.com/wordpress/<?php the_permalink($post->ID); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h4>
</header>
</div><!-- content -->
</article><!-- entry-item -->
<?php
}
echo '</div></div>';
echo '<div class="clear"></div>';
}
}
$post = $orig_post;
wp_reset_postdata();
}
endif;
Una vez que se ha copiado el código en el functions.php
, se tuvo que agregar una etiqueta en el single.php
o la plantilla que contiene el bucle de publicaciones individuales.
<?php evolution_related_posts(); ?>
Para asegurarse de que todo se vea bien, se requiere algo de CSS:
.related-posts {
display: flex;
}
.related-posts .entry-title {
font-size: 1rem;
}
.related-posts .cat {
color: #ba9e30;
font-size: 0.85rem;
}
.related-posts .entry-item {
width: 31%;
margin-right: 3.5%;
position: relative;
float: left;
}
.related-posts .entry-item.third {
margin-right: 0;
}
.related-posts a img:hover {
opacity: .85;
}
.entry-related {
padding-bottom: 10px;
border-bottom: 1px solid #ddd;
margin-bottom: 20px
}
.related-wrap {
margin-bottom: 70px;
}
20 – Creación de un sitemap.XML sin un complemento
En combinación con el Consola de búsqueda de Google (anteriormente Herramientas para webmasters), el sitemap.xml permite una indexación rápida de las publicaciones de su sitio web. Anteriormente, tenía que instalar un complemento para generar un sitemap.xml. Con este código, puede renunciar al complemento.
[blue-box text=”The sitemap is created for your posts, the pages, and the images in the media library.”]
<?php
// Copy from here
/**
* Creating an own sitemap.xml without a plugin
* @author Andreas Hecht
*/
function ah_create_sitemap() {
$sitemap_posts = get_posts(array(
'numberposts' => -1,
'orderby' => 'modified',
'post_type' => array('post','page', 'attachment'), // Deine Custom Post Types hier einfügen (z.B. Portfolio)
'order' => 'DESC'
));
$sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
$sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
foreach($sitemap_posts as $post) {
setup_postdata($post);
$postdate = explode(" ", $post->post_modified);
$sitemap .= '<url>'.
'<loc>'. get_permalink($post->ID) .'</loc>'.
'<lastmod>'. $postdate[0] .'</lastmod>'.
'<changefreq>monthly</changefreq>'.
'</url>';
}
$sitemap .= '</urlset>';
$fp = fopen(ABSPATH . "sitemap.xml", 'w');
fwrite($fp, $sitemap);
fclose($fp);
}
add_action('publish_post', 'ah_create_sitemap');
add_action('publish_page', 'ah_create_sitemap');
21 – Hacer que las imágenes de las publicaciones sean obligatorias
El siguiente fragmento podría ser muy útil para blogs con varios autores, ya que hace que las imágenes de las publicaciones sean necesarias para poder publicar un artículo.
<?php
add_action('save_post', 'evolution_check_thumbnail');
add_action('admin_notices', 'evolution_thumbnail_error');
function evolution_check_thumbnail($post_id) {
// change to any custom post type
if(get_post_type($post_id) != 'post')
return;
if ( !has_post_thumbnail( $post_id ) ) {
// set a transient to show the users an admin message
set_transient( "has_post_thumbnail", "no" );
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'evolution_check_thumbnail');
// update the post set it to draft
wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
add_action('save_post', 'evolution_check_thumbnail');
} else {
delete_transient( "has_post_thumbnail" );
}
}
function evolution_thumbnail_error()
{
// check if the transient is set, and display the error message
if ( get_transient( "has_post_thumbnail" ) == "no" ) {
echo "<div id='message' class="error"><p><strong>You have to assign a post image. Without a post image, the article can't be published.</strong></p></div>";
delete_transient( "has_post_thumbnail" );
}
}
22 – Vincular cuentas de Twitter automáticamente
Si tiende a vincular cuentas de Twitter en sus publicaciones, le encantará este fragmento. Al ingresar a @account, se vinculará automáticamente la cuenta de Twitter correspondiente.
<?php
function content_twitter_mention($content) {
return preg_replace('/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/', "$1<a href="http://twitter.com/$2" target="_blank" rel="nofollow">@$2</a>", $content);
}
add_filter('the_content', 'content_twitter_mention');
add_filter('comment_text', 'content_twitter_mention');
23 – Evitar la vinculación automática en los comentarios de los usuarios
Cada URL ingresada en los comentarios se convierte automáticamente en un enlace de WordPress. Esto puede convertirse en un problema, ya que no vale la pena vincular todos esos enlaces en su blog. El siguiente fragmento convierte las URL en texto puro.
<?php
remove_filter('comment_text', 'make_clickable', 9);
24 – Cargue todo el JavaScript en el pie de página
WordPress normalmente carga JavaScript en el encabezado de su sitio web. Esto ralentiza mucho la acumulación de páginas. Con este código, todo el JavaScript se carga en el pie de página, lo que permite que el sitio se desarrolle más rápido.
<?php
/**
* @uses wp_head() and wp_enqueue_scripts()
*
*/
if ( !function_exists( 'evolution_footer_scripts' ) ) {
function evolution_footer_scripts() {
remove_action('wp_head', 'wp_print_scripts');
remove_action('wp_head', 'wp_print_head_scripts', 9);
remove_action('wp_head', 'wp_enqueue_scripts', 1);
}
}
add_action( 'wp_enqueue_scripts', 'evolution_footer_scripts' );
25 – Cree una ruta de navegación sin un complemento
No necesita un complemento sobrecargado para una navegación de ruta de navegación. Basta con unas pocas líneas de código.
<?php
// Copy from here
function ah_the_breadcrumb() {
echo '<ul id="crumbs">';
if (!is_home()) {
echo '<li><a href="';
echo get_option('home');
echo '">';
echo 'Home';
echo "</a></li>";
if (is_category() || is_single()) {
echo '<li>';
the_category(' </li><li> ');
if (is_single()) {
echo "</li><li>";
the_title();
echo '</li>';
}
} elseif (is_page()) {
echo '<li>';
echo the_title();
echo '</li>';
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
echo '</ul>';
}
La etiqueta para la invocación en el tema
En el tema, la navegación se puede integrar mediante una simple invocación de función. Los archivos correctos para hacer eso serían los header.php
, el index.php
, o la single.php
, dependiendo del tema.
<?php ah_the_breadcrumb(); ?>
26 – Mostrar tipos de publicaciones personalizadas en las categorías y etiquetas
Los tipos de publicaciones personalizadas son una herramienta extremadamente útil para el diseño de un sitio web extenso con muchas funciones. Sin embargo, no se incluyen automáticamente en las categorías y etiquetas. Si inicia una búsqueda, esto siempre le dejará un error. Estos dos fragmentos integran sus tipos de publicaciones personalizadas en la función de búsqueda de WordPress.
El fragmento de las categorías:
<?php
/**
* Results in the display of the custom post types in the categories
* @author Andreas Hecht
*/
function evolution_query_post_type($query) {
if( is_category() ) {
$post_type = get_query_var('post_type');
if($post_type)
$post_type = $post_type;
else
// Adding your post types
$post_type = array('nav_menu_item', 'post', 'posttype', 'posttype'); // don't forget nav_menu_item to allow menus to work!
$query->set('post_type',$post_type);
return $query;
}
}
add_filter('pre_get_posts', 'evolution_query_post_type');
El fragmento de las etiquetas:
<?php
/**
* Results in the display of the custom post types in the tags
* @author Andreas Hecht
*/
function evolution_tag_query_post_type($query) {
if( is_tag() ) {
$post_type = get_query_var('post_type');
if($post_type)
$post_type = $post_type;
else
// Adding your post types
$post_type = array('nav_menu_item', 'post', 'posttype', 'posttype'); // don't forget nav_menu_item to allow menus to work!
$query->set('post_type',$post_type);
return $query;
}
}
add_filter('pre_get_posts', 'evolution_tag_query_post_type');
Conclusión
Espero que hayas descubierto algunos fragmentos útiles para ti y tu WordPress. Si este artículo tiene éxito, podría continuar con un artículo sobre los fragmentos más útiles de WooCommerce. Déjame saber si eso te interesa. Y si está buscando presionar el botón fácil y tener su sitio de WordPress completamente administrado para usted, un Plan de mantenimiento de WP Buffs 24/7 puede ser una buena inversión para ti.
#Los #fragmentos #WordPress #más #útiles #funcionales