Wordpress内容在使用foreach时显示怪异

时间:2013-09-06 11:19:07

标签: php arrays wordpress foreach

我目前正在客户端wordpress网站上做一些自定义工作。我使用下面的代码来查询工作正常的数据库。但是,当我尝试显示结果时,它不能正常工作。基本上我正在尝试查询postmeta表以查找我添加的自定义字段中的信息,在这种情况下可能是我的名字,andy。一旦系统找到自定义字段值为andy的所有帖子,它就应该使用这些行的id并显示每个帖子的标题,内容和日期。这工作正常,直到我查看页面实时,基本上它是计算我的名字出现的次数,并回显所有行的信息,而我希望它只回显来自发布行的信息。任何人都可以帮助我,让我头疼!:

PHP

<?php
        require_once('dbConfig.php');

        // This variable grabs the name in the URL
        $r = get_permalink();
        $r = explode('/', $r);
        $r = array_filter($r);
        $r = array_merge($r, array()); //reset keys
        $code = $r[3];

        $getName = preg_replace("/[^a-zA-Z0-9\s]/", "", $code);
        $name = $db->real_escape_string($getName);
        ?>

        <?php
        $allposts = $wpdb->get_results( $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_value = %s", $name) );
        foreach ($allposts as $singlepost) { 
            $wpPosts = $wpdb->get_row( $wpdb->prepare("SELECT post_title, post_content, post_date_gmt FROM $wpdb->posts WHERE ID = %d AND post_status = 'publish' AND post_type='post' ORDER BY ID DESC", $singlepost->post_id) );
            $wpPostsDate = new DateTime($wpPosts->post_date_gmt);
            echo '<h1>'.$wpPosts->post_title.'</h1><br>';
            echo 'Post Content: '.$wpPosts->post_content.'<br>';
            echo 'Post Date: '.$wpPostsDate->format('jS F Y').'<br><br>';
        }
        ?>

2 个答案:

答案 0 :(得分:1)

首先确保在运行select查询之前$name中有确切的值,然后尝试这样的单个连接查询:

$sql = $wpdb->prepare("
        SELECT
          p.post_title, p.post_content, p.post_date_gmt
        FROM
          $wpdb->posts p
        RIGHT JOIN $wpdb->postmeta pm ON (pm.post_id = p.ID)
        WHERE pm.meta_value = %s AND p.post_status = 'publish'
        AND p.post_type = 'post' ORDER BY p.ID DESC
    ", $name);

$allposts = $wpdb->get_results($sql);

foreach ($allposts as $singlepost) {
    $singlepostDate = new DateTime($singlepost->post_date_gmt);
    echo '<h1>'.$singlepost->post_title.'</h1><br>';
    echo 'Post Content: '.$singlepost->post_content.'<br>';
    echo 'Post Date: '.$singlepostDate->format('jS F Y').'<br><br>';
}

答案 1 :(得分:1)

有时你只需要一个简单的方法:

require_once('dbConfig.php');
            // This variable grabs the name in the URL
            $r = get_permalink();
            $r = explode('/', $r);
            $r = array_filter($r);
            $r = array_merge($r, array()); //reset keys
            $code = $r[3];

            $getName = preg_replace("/[^a-zA-Z0-9\s]/", "", $code);
            $name = $db->real_escape_string($getName);

            $pages = get_posts('meta_key=post_author&meta_value='.$name.'&post_type=post&post_status=publish');

            $output = '';

            foreach($pages as $value){

                $output .= "<h1>".$value->post_title."</h1>";
                $output .= "<p>".$value->post_content."</p>";
            } 

            echo $output;

完全符合我的要求:)