如何使用此自定义mysql查询将数据检索为Wp_query对象?

时间:2017-04-25 10:38:52

标签: php mysql wordpress

SELECT 
    IF (POSITION('Villa' IN p.post_title )>=1,
        SUBSTRING(p.post_title, 7), post_title) AS 'Title',
    p.post_title, 
    p.ID, 
    p.post_content
FROM wp_posts p INNER JOIN wp_term_relationships tr
 ON p.ID=tr.object_id where tr.term_taxonomy_id=4
    and p.post_status='publish' 
ORDER BY Title ASC;

我可以运行以上查询来获取数据" wpdb" 功能如

$wpdb->get_results($query);

但我需要将上述结果作为Wp_query对象返回,因为我想使用像get_the_excerpt()这样的函数

3 个答案:

答案 0 :(得分:0)

orderby参数接受post__in排序值作为对返回的帖子进行排序的可能方式。将orderby设置为post__in后,帖子将按照输入post__in参数的顺序返回。

以下代码

 args = [
         'post__in' =>[3, 1, 2],
        'orderby' => 'post__in'
        ];

$q = new WP_Query( $args );

将按以下顺序返回帖子1,2和3

  3,1,2

答案 1 :(得分:0)

试试这段代码,

 $args = array(
            'post_type' => $post_type,
            'posts_per_page' => -1,
            'post_status'=>'publish',
            'orderby'=>'title',
            'order'   => 'ASC',
            'tax_query' => array(
                array(
                    'taxonomy' => $taxonomy,
                    'field' => 'id',
                    'terms' => 4
                )
            )  
        );
        $query = new WP_Query($args);
        $query_posts = $query->posts;
        var_dump($query_posts);

答案 2 :(得分:0)

你可以获取你的WPDB结果并使用像这样的帖子函数......

global $wpdb;
global $post;

$query = "SELECT 
    IF (POSITION('Villa' IN p.post_title )>=1,
        SUBSTRING(p.post_title, 7), post_title) AS 'Title',
    p.post_title, 
    p.ID, 
    p.post_content
FROM wp_posts p INNER JOIN wp_term_relationships tr
ON p.ID=tr.object_id where tr.term_taxonomy_id=4
    and p.post_status='publish' 
ORDER BY Title ASC;"

$result = $wpdb->get_results( $query );

foreach( $result as $post )
{
    setup_postdata( $post );
    echo "<div>" . get_the_excerpt() . "</div>";
}

确保将$ post设置为全局。