Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |not checked

Entendiendo el loop de WordPress

El código principal en WordPress es su loop y es de vital importancia entenderlo, en muchos libros se da como utilizar el loop de WordPress, pero no ahondan demasiado en el tema aquí trataré de dar el tema un poco más en profundidad.

Para tocar este tema en profundidad crearé un tema muy simple de WordPress el cual tenga solo 2 archivos php(index.php, functions.php) y style.css.

El loop de WordPress

Primero veamos como es el loop de WordPress y que funciones podemos llamar en él.

El siguiente código es sacado de codex.wordpress.org y es un loop básico.

<?php 
if ( have_posts() ) {
	while ( have_posts() ) {
		the_post(); 
		//
		// Post Content here
		//
	} // end while
} // end if
?>

Si se fija bien estamos chequeando si tiene posts y mientras los tenga continuara corriendo el loop de while y mientras recorro voy obteniendo los post,¿No?

Creemos un mini tema para ver que lo antes deducido es correcto. Nuestro tema se llamará no y tendrá los siguientes archivos:

  • style.css
  • index.php
  • functions.php

De estos archivos el que nos importa en este tema es index.php que es donde probaremos el loop, en style pondremos el comentario que diga que es nuestro tema y un poco de información más. En tanto a function pondremos que soporte tendrá.

functions.php
<?php
 
/**
 * First, let's set the maximum content width based on the theme's design and stylesheet.
 * This will limit the width of all uploaded images and embeds.
 */
if ( ! isset( $content_width ) )
    $content_width = 800; /* pixels */
 
if ( ! function_exists( 'no_setup' ) ) :
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which runs
 * before the init hook. The init hook is too late for some features, such as indicating
 * support post thumbnails.
 */
function no_setup() {
 
    /**
     * Make theme available for translation.
     * Translations can be placed in the /languages/ directory.
     */
    load_theme_textdomain( 'no', get_template_directory() . '/languages' );
 
    /**
     * Add default posts and comments RSS feed links to <head>.
     */
    add_theme_support( 'automatic-feed-links' );
 
    /**
     * Enable support for post thumbnails and featured images.
     */
    add_theme_support( 'post-thumbnails' );
 
    /**
     * Add support for two custom navigation menus.
     */
    register_nav_menus( array(
        'primary'   => __( 'Primary Menu', 'no' ),
        'secondary' => __('Secondary Menu', 'no' )
    ) );
 
    /**
     * Enable support for the following post formats:
     * aside, gallery, quote, image, and video
     */
    add_theme_support( 'post-formats', array ( 'aside', 'gallery', 'quote', 'image', 'video' ) );
}
endif; // no_setup
add_action( 'after_setup_theme', 'no_setup' );
index.php
<?php
/**this is a basic wordpress loop */

get_header();

if ( have_posts() ) {

    // Load posts loop.
    while ( have_posts() ) {
        the_post();?>
        <h1><?php the_title();?></h1>
        <?php the_content();
    }
}
else{
    echo "no post to be showed";
}
get_footer();

Como puede ver he agregado 2 líneas para que nos devuelva el título y el contenido del post ya que the_post() no devolverá algo que se imprima en pantalla.

style.css
@charset "UTF-8";

/*
Theme Name: no
Theme URI: https://blastcoding.com/themes/no
Author: Blastcoding.com
Author URI: https://blastcoding.com/
Description: no is a theme to learn wordpress
Requires at least: 5.3
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: no
*/

En este tema ponga la data que se te ocurra, es un tema demasiado simple para poner una licencia o algo por el estilo.

En lo último de esta prueba de nuestro loop tendremos que escribir algunos post, utiliza lorem ipsum para hacerlo más rápido y un título cualquiera.

Al testear nos quedaría algo así:

¿Cómo hago para que solo me muestre un post?

Bueno dentro de WordPress podemos decir que detecta si estamos entrando a un post o no según la URL que le demos. Hagamos un ejemplo de esto Toma index.php y cámbialo de la siguiente manera:

<?php
/**this is a basic wordpress loop */

get_header();

if ( have_posts() ) {

    // Load posts loop.
    while ( have_posts() ) {
        the_post();?>
        <a href="<?php the_permalink();?>">
        <h1><?php the_title();?></h1>
        </a>
        <?php the_content();
    }
}
else{
    echo "no post to be showed";
}
get_footer();

Como puede ver he puesto un link al post correspondiente en el header de cada post de esta manera podrá probar lo antes mencionado

Work in progress- los textos siguientes pueden tener falta de ortografía y puede que también tenga conceptos errados.

MULTIPLE LOOP

En esta parte de este artículo veremos como hacer multiple loops en una misma página, ahora ¿que tiene de distinto hacer múltiple loops?

Tomemos el archivo index.php que hicimos y llamemosle 2 loops uno a continuación del otro.

<html>
	<body>	
<?php
/**this is a basic wordpress loop */

get_header();

$args = array( 'category_name' => 'postres','posts_per_page' => -1  );
$myposts = new WP_Query($args);

if ($myposts->have_posts() ) {

	// Load posts loop.
	while ( $myposts->have_posts() ) {
		$myposts->the_post();?>
		<a href="<?php the_permalink();?>">
		<h1><?php the_title();?></h1>
		</a>
		<?php the_content();
	}
}
else{
	echo "no post to be showed";
}

if ( have_posts() ) {

	// Load posts loop.
	while ( have_posts() ) {
		the_post();?>
		<a href="<?php the_permalink();?>">
		<h1><?php the_title();?></h1>
		</a>
		<?php the_content();
	}
}
else{
	echo "no post to be showed";
}
get_footer();
?>
<body>
</head>

No ocurrirá nada y se ejecutará el loop, esto no siempre fue de esta manera y es posible que en algunos temas os topes con la función rewind_post() está lo que hace es resetear el post query y el loop en sí.

Actualmente rewind_post() sigue siendo utilizada internamente en have_posts().

Category: wordpress
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category