WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] help with $WPDB object (3 posts)

  1. kc11
    Member
    Posted 3 years ago #

    Hello All,

    I have been reading in the codex about the $wpdb object at:

    http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

    On this page , they give the following example of a query:

    <?php
    
     $querystr = "
        SELECT wposts.*
        FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
        WHERE wposts.ID = wpostmeta.post_id
        AND wpostmeta.meta_key = 'tag'
        AND wpostmeta.meta_value = 'email'
        AND wposts.post_status = 'publish'
        AND wposts.post_type = 'post'
        ORDER BY wposts.post_date DESC
     ";
    
     $pageposts = $wpdb->get_results($querystr, OBJECT);
    
     ?>

    I must apologize but my understanding of SQL is limited. In the 3rd line ( FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta ) does 'FROM $wpdb->posts wposts' mean "select from the table 'posts' and put the recordset into the 'wposts' object" ?

    I don't understand what wposts is.

    Thank you in advance,

    KC

  2. Mark / t31os
    Moderator
    Posted 3 years ago #

    wposts is an alias for $wpdb->posts.

    When you reference tables over and over in a mysql statement it's sometimes easier to type an alias out then to keep typing out the full table name(or a variable)..

    Let me give you an example of the differences between using and not using an alias.

    // Without an alias
    $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post'");
    
    // With an alias
    $wpdb->get_results("SELECT * FROM $wpdb->posts AS wposts WHERE wposts.post_status = 'publish' AND wposts.post_type = 'post'");
    
    // With an alias but without AS keyword
    $wpdb->get_results("SELECT * FROM $wpdb->posts wposts WHERE wposts.post_status = 'publish' AND wposts.post_type = 'post'");

    The AS keyword is optional in MySQL.

  3. kc11
    Member
    Posted 3 years ago #

    Thank you Mark. That clears it up.

    KC

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.