Tutorial and examples to learn wordpress sql using global $wpdb, get row, get results, delete row and update row in wordpress sql database.
WordPress SQL
We will learn how to use global $wpdb in wordpress, we will learn how to get row, get results, update row and delete row in wordpress sql database, easy examples to learn wordpress sql.
Get Row
Using get_row() function, we will get row in wordpress sql easily, example:
function WPTime_get_row(){ global $wpdb; $get_row = $wpdb->get_row("SELECT post_name FROM $wpdb->posts WHERE post_type = 'post' AND ID = 2426"); echo $get_row->post_name; // print post title for post ID number 2426 }
Get Results
Using get_results() function, we will get results in wordpress sql easily, for example get results by post ID:
function WPTime_get_results_by_id(){ global $wpdb; $get_posts = $wpdb->get_results(" SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' AND ID = 2426 "); foreach ($get_posts as $get_post) { echo $get_post->post_name; // print post title for post ID number 2426 echo '<br>'; echo $get_post->post_date; // print post date for post ID number 2426 } }
Get 2 random posts:
function WPTime_get_random_posts(){ global $wpdb; $get_posts = $wpdb->get_results(" SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY RAND() LIMIT 2"); foreach ($get_posts as $get_post) { $post_id = $get_post->ID; // get posts IDs echo '<li><a href="'.get_permalink($post_id).'">'.get_the_title($post_id).'</a></li>'; } }
Update Row
Using query() function, we will update row in wordpress sql easily, for example close all comment status:
function WPTime_update_row(){ global $wpdb; $wpdb->query(" UPDATE $wpdb->posts SET comment_status = 'close' WHERE comment_status = 'open' "); // now all comments will be closed }
Delete Row
Using delete() function, we will delete row in wordpress sql easily, for example remove all spam comments:
function WPTime_delete_row(){ global $wpdb; $wpdb->delete( 'wp_comments', array( 'comment_approved' => 'spam' ) ); // remove all spam comments }