$wpdb->get_var no devuelve ningún resultado

2 jul 2012, 23:54:09
Vistas: 17.1K
Votos: 2

Ejecuté mysql y confirmé que esta consulta devuelve un resultado:

mysql> SELECT * FROM wp_posts WHERE post_parent = 68 AND post_type = 'attachment' AND post_name = 'side-logo-auto2' LIMIT 1;
1 row in set (0.00 sec)

En mi plantilla, intento lo mismo:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();

    //$wpdb->posts es la tabla wp_posts
    //$post->ID es el post actual de tipo página,
    //asociado con la página de esta plantilla

    global $wpdb;
    $image = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT * FROM $wpdb->posts
             WHERE post_parent = %d
             AND post_type = %s
             AND post_name = %s
             LIMIT 1
            ",
            $post->ID,
            'attachment',
            'side-logo-auto2'
        )
    );
    echo "El ID de la imagen es {$image->ID}";
    echo wp_get_attachment_image($image->ID);

endwhile; endif; ?> 

$post->ID devuelve 68. Sin embargo, el valor asignado a $image no es el registro, sino null.

0
Todas las respuestas a la pregunta 1
2

$wpdb->get_var devuelve una sola variable, pero tu sentencia SQL tiene SELECT * que devuelve una fila con múltiples columnas.

Necesitas cambiar tu sentencia SQL a SELECT ID ... en lugar de SELECT * ...

3 jul 2012 00:12:02
Comentarios

Esto devolvería solo el id, pero en realidad era get_row lo que estaba buscando.

JohnMerlino JohnMerlino
5 jul 2012 22:36:57