Show Recent Posts using SQL Query WordPress

Hello friends, welcome to my another blog post how to show recent posts using SQL Query WordPress. If you want to create your own widget to show recent posts from your own style or if you do not use WordPress query post then you have the option to fetch your post from your database table and display them. Today I will show you how to do that.

This function is useful when you need to display content, excerpt, custom fields, or anything related to the post beyond it’s link and title. Copy ans paste the below code in your theme functions.php page.



function get_recent_posts($no_posts = 10, $excerpts = true) {

   global $wpdb;

   $request = "SELECT ID, post_title, post_excerpt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type='post' ORDER BY post_date DESC LIMIT $no_posts";

   $posts = $wpdb->get_results($request);

   if($posts) {

               foreach ($posts as $post) {
						/* Show title */
						$post_title = stripslashes($post->post_title);
						/* Show Permalink */
						$permalink = get_permalink($post->ID);
						/* Show Custom Field */
						$custom_field_one = get_post_meta( $post->ID, 'field_key_one', true );
						$custom_field_two = get_post_meta( $post->ID, 'field_key_two', true );
						/* Show Featured Image */
						$post_thumbnail_id = get_post_thumbnail_id($post->ID);
						$thumb_url_array = wp_get_attachment_image_src($post_thumbnail_id, array(100, 100), true);
						$thumb_url = $thumb_url_array[0];
                       $output .= '<li><h2><a href="' . $permalink . '" >' . htmlspecialchars($post_title) . '</a></h2>';

                       if($excerpts) {
                               $output.= '<br />' . stripslashes($post->post_excerpt);
                       }

                       $output .= '</li>';
               }

       } else {
               $output .= '<li>No posts found</li>';
       }

   echo $output;
}

Now you can paste below code in the sidebar or wherever you like the recent posts to list

By default it show 10 posts with excerpt but you can change it by passing parameters into the function like this It will show 5 posts excluding excerpts.

Thank you for your time. Now you know how to show recent posts using SQL Query WordPress.

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •