Categoria: Plugins

  • Enviar variáveis para template-parts

    A function get_template_part() é uma forma segura de fazer includes no tema, pois não gera erros em caso de não encontrar o arquivo e permite fallback para um template genérico. Além disso, o seu uso facilita no uso dos Child Themes, já que permite dentro tema filho, fazer o include de um template-part do Tema Pai.

    Mas uma coisa a se atentar, é como passar variáveis para um template-part. Quando usamos includes comuns do PHP, as variáveis declaradas no arquivo parent, estão disponíveis no arquivo incluído, mas isso não acontece com o get_template_part(). No exemplo abaixo, a variável $custom_intro não estará disponível para o arquivo special.php:

    if ( have_posts() ) {
    	while ( have_posts() ) {
    		the_post();
    		$custom_intro = get_post_meta( $post->ID, 'custom_intro', true );
    		get_template_part( 'template-part', 'special' );
    	}
    } else {
    	get_template_part( 'template-part', 'default' );
    }
    <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    	<header class="entry-header">
    		<h2 class="entry-title"><?php the_title( sprintf( '<a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a>' ); ?></h2>
    	</header>
    
    	<div class="entry-content">
    		<?php
    		echo $custom_intro;
    		the_content();
    		?>
    	</div>
    </article>

    Em special.php irá gerar o erro Notice: Undefined variable: custom_intro. Para que $custom_intro fique disponível, é necessário enviar as variáveis pelo 3º parâmetro $args, cuidando para seja enviado como array associativo:

    if ( have_posts() ) {
    	while ( have_posts() ) {
    		the_post();
    		$custom_intro = get_post_meta( $post->ID, 'custom_intro', true );
    		$args = array( 'custom_intro' => $custom_intro );
    		get_template_part( 'template-part', 'special', $args );
    	}
    } else {
    	get_template_part( 'template-part', 'default' );
    }

    Dessa forma, o valor de $custom_intro, será acessível no template através de $args['custom_intro']:

    <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    	<header class="entry-header">
    		<h2 class="entry-title"><?php the_title( sprintf( '<a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a>' ); ?></h2>
    	</header>
    
    	<div class="entry-content">
    		<?php
    		echo $args['custom_intro'];
    		the_content();
    		?>
    	</div>
    </article>