Declaración condicional if ($post->ID == get_the_ID()) no funciona

14 mar 2011, 21:21:23
Vistas: 16.6K
Votos: 1

El siguiente código debería leer: Si el tipo de post personalizado actual (bbp_forum) es el que se está mostrando, asignar la clase 'current' a su respectiva etiqueta <li>. Pero por alguna razón la clase 'current' (para resaltar el enlace del bbp_forum actual) se está mostrando en todas las etiquetas <li>:

Captura mostrando el problema de la clase current aplicada incorrectamente

<body <?php body_class(); ?>>
<div id="wrapper" class="hfeed">
    <div id="header">
        <div id="masthead">
            <div id="branding" role="banner">
                <h1><a href="<?php echo home_url( '/' ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
            </div><!-- #branding -->
            <div id="access" role="navigation">
                <?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?>
            </div><!-- #access -->
        </div><!-- #masthead -->
        <ul id="forums">
          <?php global $post; $cat_posts = get_posts('post_type=bbp_forum');
          foreach($cat_posts as $post) : ?>
            <li <?php if($post->ID == get_the_ID()){ ?>class="current" <?php } ?>>
                <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Enlace permanente a %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a>
             </li>
          <?php endforeach; ?>
        </ul><!-- #access -->
    </div><!-- #header -->

    <div id="main">

¿Alguna sugerencia?

0
Todas las respuestas a la pregunta 1
0

La expresión siempre será verdadera. Observa get_the_ID();

function get_the_ID() {
    global $post;
    return $post->ID;
}

Por lo tanto, tu código efectivamente se ejecuta como:

if ( $post->ID == $post->ID ) // ¡siempre verdadero!

En lugar de eso, guarda el ID del post principal en una variable, y luego compara con esa variable.

<?php

global $post;

/**
 * @var int ID del post actual.
 */
$the_post_ID = $post->ID;

/**
 * @var array Todos los posts para bbp_forum.
 */
$cat_posts = get_posts('post_type=bbp_forum');

?>

<?php foreach ( $cat_posts as $post ) : ?>

    <li<?php if ( $post->ID == $the_post_ID ) echo ' class="current"'; ?>>
        <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Enlace permanente a %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a>
    </li>

<?php endforeach; ?>
14 mar 2011 21:30:00