我试图从Wordpress获得两个包含精选图片的最新帖子。需要获得帖子标题,内容(字符限制)和特色图片。到目前为止,我有这个,缺少的是特色图片。
<div class="block block-blog block-recent-posts">
<?php $resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = "SELECT `id`, `post_title`,`post_name` ,`post_content`, `comment_count` FROM `wp_posts` WHERE `post_type`='post' ORDER BY `comment_count` DESC LIMIT 10";
$results = $readConnection->fetchAll($query);
?>
<ul>
<?php
$counter = 0;
foreach($results as $row) { ?>
<?php if($row['post_title']!='Auto Draft'): ?>
<li class="item">
<a href="<?php echo $this->getUrl('news/').$row['post_name'];?>"> <?php echo $row['post_title'];?></a>
<p class="blog-content"> <?php $content = $row['post_content']; echo $string = substr($content,0,220); if(strlen($content)>220){echo "...";} ?></a></p>
</li>
<?php endif; ?>
<?php
if($counter == 2)
{
break;
}
$counter++;
}
?>
</ul>
答案 0 :(得分:0)
试试这个:
我已更新您的查询并添加了另一个查询以获取帖子图片网址:
<div class="block block-blog block-recent-posts">
<?php $resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = "SELECT p.id,p.post_title,p.post_name ,p.post_content,p.comment_count,pm.meta_value FROM wp_postmeta AS pm INNER JOIN wp_posts AS p ON pm.post_id=p.ID WHERE pm.meta_key = '_thumbnail_id' AND p.post_type='post' ORDER BY p.post_date DESC LIMIT 10";
$results = $readConnection->fetchAll($query);
?>
<ul>
<?php
$counter = 0;
foreach($results as $row) { ?>
<?php if($row['post_title']!='Auto Draft'):
//Get url from pm.meta_value
/********/
$readConnection1 = $resource->getConnection('core_read');
$query1 ="SELECT * FROM `wp_postmeta` WHERE `post_id` = '".$row['meta_value']."' AND meta_key='_wp_attached_file'";
$results1 = $readConnection->fetchAll($query1);
$url='www.yoursite.com/wp-content/uploads/'.($results1[0]['meta_value']);
echo $url; //YOUR URL just set your site name
//So final url YOUR--> SITENAME/wp-content/uploads/pathfromquery
?>
<li class="item">
<a href="<?php echo $this->getUrl('news/').$row['post_name'];?>"> <?php echo $row['post_title'];?></a>
<p class="blog-content"> <?php $content = $row['post_content']; echo $string = substr($content,0,220); if(strlen($content)>220){echo "...";} ?></a></p>
</li>
<?php endif; ?>
<?php
if($counter == 2)
{
break;
}
$counter++;
}
?>
</ul>
答案 1 :(得分:0)
你不应该在这里使用原始SQL。作为一种解决方法,你不能做以下任何一种:
1)选择2个以上的帖子(例如5个)并循环浏览它们并显示2个具有特色图像的帖子
2)确保所有帖子都有精选图片,然后选择前2个帖子
3)使用一组帖子,然后将自定义SQL添加到该帖子中。
此代码将获得2个帖子并将_thumbnail_id添加到集合中。你可以添加一些代码来检查这个字段是否存在(使用$ posts-&gt; load(true)来调试SQL查询和$ posts-&gt; getSelect() - &gt; where()来添加自定义过滤器)< / p>
(emojicode)