Pregunta

I'd like to be able to pre-populate all occurances of the get_tempate_part $args when setting up a theme.

get_template_part( string $slug, string $name = null, array *$args* = array() )

Several action hooks exist within the get_template_part function and within locate_template which is also called by get_template_part, get_header, get_footer and the like but no filters are applied. The best I've been able to fashions is to modify every instance of my themes call to get_template_part like so:

<?php get_template_part( 'views/loop', 'index', apply_filters( 'filter_template_part_args', [], 'loop' ) ); ?>

and run a custom filter like so:

add_filter( 'filter_template_part_args', function( $args, $slug, $name = '' ) {

    $defaults = [
        'id'        => esc_attr( basename( $slug ) ),
        'tag'       => 'div',
        'class'     => '',
        'container' => 'container',
        'row'       => 'row',
    ];

    return \wp_parse_args( $args, $defaults );
    ;

} );

the above function work around - whilst being maintenance heavy – works for the individual teamplate_part calls made in the theme, but fails for existing calls from wordpress defaults (get_footer, get_header, etc)

Am I missing some key bit of info? Yes, get_header() will except an $args param – but my theme is rapidly filling up with multiple code chunks that make extensibility painful and very un-DRY

¿Fue útil?

Solución

There's no such filter, so what you're doing is about the best you can do. However, you can optimise a bit by creating functions that wrap the template functions while applying your filter:

add_filter(
    'filter_template_part_args',
    function( $args, $slug, $name = null ) {
        $args = wp_parse_args(
            $args,
            [
                'id'        => esc_attr( basename( $slug ) ),
                'tag'       => 'div',
                'class'     => '',
                'container' => 'container',
                'row'       => 'row',
            ]
        );

        return $args;
    }
)

function mytheme_get_template_part( $slug, $name = null, $args = [] ) {
    $args = apply_filters( 'filter_template_part_args', $args, $slug, $name );

    get_template_part( $slug, $name, $args );
}

function mytheme_get_header( $name = null, $args = [] ) {
    $args = apply_filters( 'filter_template_part_args', $args, 'header', $name );

    get_header( $name, $args );
}

Then you can just do the same with get_sidebar() and get_footer(), and you should be covered for all the main template functions:

function mytheme_get_footer( $name = null, $args = [] ) {
    $args = apply_filters( 'filter_template_part_args', $args, 'footer', $name );

    get_footer( $name, $args );
}

function mytheme_get_sidebar( $name = null, $args = [] ) {
    $args = apply_filters( 'filter_template_part_args', $args, 'sidebar', $name );

    get_sidebar( $name, $args );
}
Licenciado bajo: CC-BY-SA con atribución
scroll top