Home WordpressWordpress Developer How to use $wpdb access database

How to use $wpdb access database

by Ker

$wpdb is a global object that lets us talk to the database with the help of different build-in methods. The below example will use one of the methods called get_results().

When querying the SQL, we need to know the WordPress table name and field. How do we know the table name and table field? Check this doc: https://codex.wordpress.org/Database_Description

<?php 
         //Get list from a custom post type called : udemy_list 
         
        global $wpdb;

        $list_query = $wpdb->get_results("SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = 'udemy_list' AND post_status IN ('draft', 'publish') ");

        //dynamic display the list items

        if(!is_null($list_query)) :
            echo '
            <div class="udemy-field-container">
                <label for="">List</label>
                <ul>';  
                    foreach($list_query as $list) {
                        echo '<li><label for=""><input type="checkbox" name="udemy_list" value="">' . $list->post_title . '</label></li>';
                    }
                echo '</ul>
            </div>';
        endif
    ?>

For more reference:

Related Videos

Leave a Comment

Our mission: to help people learn web development and leverage the power of WordPress.