0

我目前正在客户的 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>';
        }
        ?>
4

2 回答 2

1

First be sure you have exact value in $name before running select query and then try a single joined query like this:

$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>';
}
于 2013-09-06T11:50:04.963 回答
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;

完全按照我想要的方式工作:)

于 2013-09-06T13:56:12.723 回答