Risoluzione problema: $wpdb->get_var non restituisce risultati

2 lug 2012, 23:54:09
Visualizzazioni: 17.1K
Voti: 2

Ho eseguito mysql e confermato che questa query restituisce un risultato:

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)

Nel mio template, provo la stessa cosa:

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

    //$wpdb->posts è la tabella wp_posts
    //$post->ID è il post corrente di tipo page, 
    //associato alla pagina di questo template

    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 "L'ID dell'immagine è {$image->ID}";
    echo wp_get_attachment_image($image->ID);

endwhile; endif; ?>

$post->ID restituisce 68. Tuttavia, il valore assegnato a $image non è il record, ma piuttosto null.

0
Tutte le risposte alla domanda 1
2

$wpdb->get_var restituisce una singola variabile, ma la tua istruzione SQL contiene SELECT * che restituisce una riga con più colonne.

Devi modificare la tua istruzione SQL in SELECT ID ... invece di SELECT * ...

3 lug 2012 00:12:02
Commenti

Questo restituirebbe solo l'id, ma in realtà era get_row quello che stavo cercando.

JohnMerlino JohnMerlino
5 lug 2012 22:36:57