//MySQL Username
$user = "myuser";
//MySQL Password
$pass = "mypass";
//MySQL Database Name
$database = "mydb";
//Number of posts you want to have appear
$numOfPosts = 7;

//Setup connection
$mysqli = new mysqli("localhost", $user, $pass, $database);
$mysqli->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());

$limit = $numOfPosts;
$sql = "SELECT * FROM wp_posts WHERE post_type = 'post' AND post_status IN ( 'draft', 'publish', 'future', 'pending', 'private','attachment' ) ORDER BY post_date DESC LIMIT $limit";
$result = $mysqli->query($sql);
while ($row = $result->fetch_object()) {
  echo '<ul>';
    echo '<li><a href="'.$row->guid.'" title="'.$row->post_title.'"target="_blank">'.$row->post_title.'</a></li>';
  echo '</ul>';

  • I changed the database connection information to something generic. Never post those credentials online and you should log in to your server and change that information immediately. – s_ha_dum Nov 30 '13 at 5:04
  • Is there any specific reason for not using Wordpress database functions? – Chittaranjan Nov 30 '13 at 5:23

You do not need to be messing with the database connection. WordPress provide a database object called $wpdb.

It is not really clear what you are doing. Your title reads "help me select thumb", but your code is actually pulling a lot of different post statuses, not thumbnails. In fact, your code does not have anything to do with thumbnails at all, that I can tell, except that some attachments are thumbnails.

This will pull and display thumbnails only.

$numOfPosts = 10;
$thumbs = $wpdb->get_col("SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_thumbnail_id' LIMIT {$numOfPosts}");
foreach ($thumbs as $thumb) {
  echo wp_get_attachment_image($thumb); 

You can use your own SQL if need be...

$sql = "SELECT * FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status IN ( 'draft', 'publish', 'future', 'pending', 'private','attachment' ) ORDER BY post_date DESC LIMIT $limit";
$result = $wpdb->get_results($sql);

I am fairly sure you could do this with WP_Query though. Something like:

$numOfPosts = 10;
$thumbs = new WP_Query(
    'posts_per_page' => $numOfPosts,
    'post_type' => 'post',
    'post_status' => array( 'draft', 'publish', 'future', 'pending', 'private','attachment' ),
if ($thumbs->have_posts()) {
  while ($thumbs->have_posts()) {
    echo '<ul>';
      echo '<li><a href="'.get_permalink().'" title="'.get_the_title().'"target="_blank">'.get_the_title().'</a></li>';
    echo '</ul>';

Again, I am not really sure what you are trying to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.