Deprecated: Return type of MGLInstagramGallery_Plugin::offsetExists($offset) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /home/mageekla/public_html/polsola/wp-content/plugins/mgl-instagram-gallery/src/MGLInstagramGallery/Plugin.php on line 14

Deprecated: Return type of MGLInstagramGallery_Plugin::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /home/mageekla/public_html/polsola/wp-content/plugins/mgl-instagram-gallery/src/MGLInstagramGallery/Plugin.php on line 22

Deprecated: Return type of MGLInstagramGallery_Plugin::offsetSet($offset, $value) should either be compatible with ArrayAccess::offsetSet(mixed $offset, mixed $value): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /home/mageekla/public_html/polsola/wp-content/plugins/mgl-instagram-gallery/src/MGLInstagramGallery/Plugin.php on line 10

Deprecated: Return type of MGLInstagramGallery_Plugin::offsetUnset($offset) should either be compatible with ArrayAccess::offsetUnset(mixed $offset): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /home/mageekla/public_html/polsola/wp-content/plugins/mgl-instagram-gallery/src/MGLInstagramGallery/Plugin.php on line 18

Deprecated: Optional parameter $content declared before required parameter $tagName is implicitly treated as a required parameter in /home/mageekla/public_html/polsola/wp-content/plugins/mgl-instagram-gallery/src/MGLInstagramGallery/Shortcode/Controller.php on line 102
Cómo utilizar el get_template_part con variables

Un pequeño truco rápido para cuando necesitamos incluir una parte de nuestro WordPress

Por ejemplo, el típico bucle para mostrar las noticias:

El bucle

<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
 <?php get_template_part('loop'); ?>
<?php endwhile; endif; ?>

El problema

Esta perfecto, el problema viene si por ejemplo queremos mostrar el número de la entrada actual, podríamos hacer esto:

$index = 0;
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
 <?php get_template_part('loop'); ?>
 <?php $index++; ?>
<?php endwhile; endif; ?>

Pero si probamos a acceder $index dentro del archivo loop.php nos dará error

La solución

Para poder acceder a la variable, debemos cambiar un poco el código:

$index = 0;
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
 <?php include(locate_template('loop.php')); ?>
 <?php $index++; ?>
<?php endwhile; endif; ?>

De esta forma la variable $index es accesible des de dentro del archivo loop.php 🙂

Deja una respuesta

diez − cuatro =