get template part – Filter get_template_part() $args array

Question

I’d like to be able to globally pre-populate 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

0
dj.cowan 3 weeks 2021-03-26T08:09:38-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse