帮我从SQL中选择缩略图并使用

时间:2013-11-30 作者:user43324
//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());
exit();
}

$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>\';

}
1 个回复
SO网友:s_ha_dum

您不需要搞乱数据库连接。WordPress提供一个名为$wpdb.

现在还不清楚你在做什么。你的标题是“帮助我选择缩略图”,但你的代码实际上是在拉很多不同的帖子状态,而不是缩略图。事实上,我可以告诉你,你的代码与缩略图没有任何关系,只是有些附件是缩略图。

这将仅拉动和显示缩略图。

$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); 
}
如果需要,您可以使用自己的SQL。。。

$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);
我很确定你可以用WP_Query 虽然类似于:

$numOfPosts = 10;
$thumbs = new WP_Query(
  array(
    \'posts_per_page\' => $numOfPosts,
    \'post_type\' => \'post\',
    \'post_status\' => array( \'draft\', \'publish\', \'future\', \'pending\', \'private\',\'attachment\' ),
  )
);
if ($thumbs->have_posts()) {
  while ($thumbs->have_posts()) {
    $thumbs->the_post();
    echo \'<ul>\';
      echo \'<li><a href="\'.get_permalink().\'" title="\'.get_the_title().\'"target="_blank">\'.get_the_title().\'</a></li>\';
    echo \'</ul>\';
  }
}
再说一遍,我真的不确定你想做什么。

结束