¿Cómo personalizar the_archive_title ()?

36

En el tema archive.php de mi hijo, tengo el siguiente código para mostrar el título de mis páginas de archivo:

    <?php
        the_archive_title( '<h1 class="page-title">', '</h1>' );
    ?>

Pero eso muestra mis títulos como "Categoría: Título de la categoría " en lugar de simplemente el título sin la "Categoría:".

Mi primer instinto fue anular get_the_archive_title() de wp-includes/general-template . Pero por lo que he leído, aparentemente no debo alterar nunca el contenido de WordPress, ni siquiera con un tema secundario.

Entonces, ¿cuál es la mejor manera de controlar la salida de the_archive_title() ?

    
pregunta fildred13 24.01.2015 - 20:57

6 respuestas

32

Si observa el código fuente de get_the_archive_title() , verá que hay un filtro suministrado, llamado get_the_archive_title , a través del cual puede filtrar la salida de la función.

Puedes usar lo siguiente para cambiar el resultado en una página de categoría

add_filter( 'get_the_archive_title', function ( $title ) {

    if( is_category() ) {

        $title = single_cat_title( '', false );

    }

    return $title;

});
    
respondido por el Pieter Goosen 25.01.2015 - 04:36
25

La respuesta aceptada funciona para eliminar el prefijo Category: de los títulos de archivo de la categoría, pero no otros tipos de taxonomía o publicaciones. Para excluir otros prefijos, hay dos opciones:

  1. Reconstruye el título para todas las variantes utilizadas en la función original get_the_archive_title() :

    // Return an alternate title, without prefix, for every type used in the get_the_archive_title().
    add_filter('get_the_archive_title', function ($title) {
        if ( is_category() ) {
            $title = single_cat_title( '', false );
        } elseif ( is_tag() ) {
            $title = single_tag_title( '', false );
        } elseif ( is_author() ) {
            $title = '<span class="vcard">' . get_the_author() . '</span>';
        } elseif ( is_year() ) {
            $title = get_the_date( _x( 'Y', 'yearly archives date format' ) );
        } elseif ( is_month() ) {
            $title = get_the_date( _x( 'F Y', 'monthly archives date format' ) );
        } elseif ( is_day() ) {
            $title = get_the_date( _x( 'F j, Y', 'daily archives date format' ) );
        } elseif ( is_tax( 'post_format' ) ) {
            if ( is_tax( 'post_format', 'post-format-aside' ) ) {
                $title = _x( 'Asides', 'post format archive title' );
            } elseif ( is_tax( 'post_format', 'post-format-gallery' ) ) {
                $title = _x( 'Galleries', 'post format archive title' );
            } elseif ( is_tax( 'post_format', 'post-format-image' ) ) {
                $title = _x( 'Images', 'post format archive title' );
            } elseif ( is_tax( 'post_format', 'post-format-video' ) ) {
                $title = _x( 'Videos', 'post format archive title' );
            } elseif ( is_tax( 'post_format', 'post-format-quote' ) ) {
                $title = _x( 'Quotes', 'post format archive title' );
            } elseif ( is_tax( 'post_format', 'post-format-link' ) ) {
                $title = _x( 'Links', 'post format archive title' );
            } elseif ( is_tax( 'post_format', 'post-format-status' ) ) {
                $title = _x( 'Statuses', 'post format archive title' );
            } elseif ( is_tax( 'post_format', 'post-format-audio' ) ) {
                $title = _x( 'Audio', 'post format archive title' );
            } elseif ( is_tax( 'post_format', 'post-format-chat' ) ) {
                $title = _x( 'Chats', 'post format archive title' );
            }
        } elseif ( is_post_type_archive() ) {
            $title = post_type_archive_title( '', false );
        } elseif ( is_tax() ) {
            $title = single_term_title( '', false );
        } else {
            $title = __( 'Archives' );
        }
        return $title;
    });
    
  2. O, simplemente elimine todo lo que parezca un prefijo de título (que puede alterar los títulos reales que contienen una palabra seguida por el carácter de dos puntos):

    // Simply remove anything that looks like an archive title prefix ("Archive:", "Foo:", "Bar:").
    add_filter('get_the_archive_title', function ($title) {
        return preg_replace('/^\w+: /', '', $title);
    });
    
respondido por el Quinn Comendant 27.09.2015 - 20:49
6

Puedes usar

echo '<h1 class="page-title">' . single_cat_title( '', false ) . '</h1>';
    
respondido por el Andrei Gheorghiu 25.01.2015 - 03:23
6

Otra opción es:

<?php echo str_replace('Brand: ','',get_the_archive_title()); ?>

Reemplazar marca: con cualquier texto que quieras eliminar.

Vale la pena ver la diferencia entre get_the_archive_title () y the_archive_title () the_archive_title () devuelve una matriz get_the_archive_title () devuelve una cadena

    
respondido por el rhysclay 25.06.2015 - 06:18
0

Ben Gillbanks tiene una buena solución que maneja todas las publicaciones Tipos y taxonomías:

function hap_hide_the_archive_title( $title ) {
// Skip if the site isn't LTR, this is visual, not functional.
// Should try to work out an elegant solution that works for both directions.
if ( is_rtl() ) {
    return $title;
}
// Split the title into parts so we can wrap them with spans.
$title_parts = explode( ': ', $title, 2 );
// Glue it back together again.
if ( ! empty( $title_parts[1] ) ) {
    $title = wp_kses(
        $title_parts[1],
        array(
            'span' => array(
                'class' => array(),
            ),
        )
    );
    $title = '<span class="screen-reader-text">' . esc_html( $title_parts[0] ) . ': </span>' . $title;
}
return $title;
}
add_filter( 'get_the_archive_title', 'hap_hide_the_archive_title' );
    
respondido por el Dan Knauss 27.01.2018 - 06:52
0

Puedes usar post_type_archive_title() para obtener el título de un archivo sin el texto "Archives:".

    
respondido por el Mark Williams 17.04.2018 - 17:23

Lea otras preguntas en las etiquetas