Wordpress从另一个db获取最新帖子

时间:2012-09-26 18:58:19

标签: php mysql database wordpress content-management-system

我正在尝试将另一个Wordpress DB的最新帖子放在我的footer.php文件中,但显然我不理解这个概念。我是WP和“循环”的新手,所以任何帮助都会受到赞赏!

<!-- .entry-content -->
<?php
$originaldb = new wpdb('db_name', 'db_password', 'db_user', 'localhost'); //This has been replaced obviously.
$newestPost = $originaldb->query("SELECT * FROM wp_posts WHERE post_status = 'publish' ORDER BY post_date DESC LIMIT 0,1;");
$newestPost = mysql_fetch_array($newestPost);
        if ($newestPost) {
        foreach ($newestPost as $newPost) {
        ?>
            <header class="entry-header">
                <div class="entry-meta">
                    <?php echo '<span class="entry-day">'.get_the_date('j').'</span><br><span class="entry-month">'.get_the_date('M').'</span>'; ?>
                </div>
                <div class="title-box">
                    <h2 class="blog-title"><a href="<?php //the_permalink(); ?>"><?php the_title(); ?></a></h2>
                    <?php echo '<a href="'.get_author_posts_url( get_the_author_meta( 'ID' ) ).'">'.get_the_author().'</a>'; ?>
                </div>
                <div class="clear"></div>
            </header>
            <div class="entry-content">
                <?php the_excerpt(); ?>
            </div>
        <?php } //end foreach ?>
    <?php } //endif ?>

2 个答案:

答案 0 :(得分:2)

以下代码将给出最后的帖子记录。

<?php
$mydb = new wpdb('root','pass','dbname','localhost');
$lastpost = $mydb->get_results("SELECT wp_posts.* FROM wp_posts 
WHERE 1=1 
AND wp_posts.post_type = 'post' 
AND (wp_posts.post_status = 'publish')
ORDER BY wp_posts.post_date DESC LIMIT 0,1");

echo $lastpost[0]->post_title;
?>

答案 1 :(得分:1)

如果我理解你要做的事情......首先,你不应该需要一个foreach循环,因为你只打算使用一个结果行。其次,为什么不直接访问$ newestPost的值作为关联数组?看看我添加了“$ newestPost ['theTitle']”来替换“the_title()”,我也为作者和内容做了类似的工作。

if ($newestPost)  {
       ?>
        <header class="entry-header">
            <div class="entry-meta">
                <?php echo '<span class="entry-day">'.get_the_date('j').'</span><br><span class="entry-month">'.get_the_date('M').'</span>'; ?>
            </div>
            <div class="title-box">
                <h2 class="blog-title"><a href="<?php //the_permalink(); ?>"><?php $newestPost['theTitle']; ?></a></h2>
                <?php echo '<a href="'.get_author_posts_url( get_the_author_meta( 'ID' ) ).'">'.$newestPost['theAuthor']).'</a>'; ?>
            </div>
            <div class="clear"></div>
        </header>
        <div class="entry-content">
            <?php echo $newestPost['theContent']; ?>
        </div>

    <?php
    } //endif ?>

您需要将“theTitle”等替换为db模式中的任何内容。希望有所帮助,我对WP不大,所以我可能会遗漏一些重要的东西,但这似乎普遍适用。

编辑:看起来使用mysql_fetch_array是no longer recommended