首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在WP_Query中使用functions.php只返回一个结果

在WP_Query中使用functions.php只返回一个结果
EN

Stack Overflow用户
提问于 2015-05-19 12:06:16
回答 1查看 3.8K关注 0票数 1

我在我的functions.php文件中编写了一个函数,它运行一个新的WP_Query类,根据它们的元键/值在我的自定义页面模板上获取一些子页面。这是一种工作,但它只返回一个结果-我知道还有更多,因为我让查询在特定的页面上正确运行,然后我把它变成一个函数。它返回了所有正确的结果,但是由于我可能需要在几个页面中使用这个功能,所以我决定将它转换为一个函数。

这是我的函数代码…

代码语言:javascript
复制
function contact_profiles($args) {

    global $post;

    $output = "";

    $the_query = new WP_Query( $args );

    while ( $the_query->have_posts() ) : $the_query->the_post();

        $output = '<div class="staff-member">'                              
        .'<a href="' . get_the_permalink() . '" title="Get in touch with ' . get_the_title() . '">' . get_the_post_thumbnail() . '</a>'
        .'<h2 class="name"><a href="' . get_the_permalink() . '" title="Get in touch with ' . get_the_title() . '">' . get_the_title() . '</a></h2>'
        .'<h3 class="job-role">' . get_post_meta( $post->ID, 'job_role', true ) . '</h3>'
        .'</div>';

    endwhile;

    wp_reset_postdata();

    return $output;
}

下面是我如何在自定义页面模板…中调用它

代码语言:javascript
复制
    $myarray = array('meta_key' => 'job_area', 'meta_value' => 'Online', 'post_type' => 'page',);

    echo contact_profiles($myarray);

我做了什么不该做的明显的事吗?是global $post位导致了问题,因为我不确定是否应该从函数文件中调用它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-19 12:48:55

最可能的情况是,在后端阅读部分中,每个页面的文章设置为1。如果没有向自定义查询传递自定义值,则默认选项get_option( 'posts_per_page' )将用作posts_per_page参数的值。

您的解决方案是将posts_per_page设置为期望的数量,或将-1设置为获取所有帖子

编辑

我以前没注意到,你的连接是错的。

代码语言:javascript
复制
$output = '<div class="staff-member">'

应该是

代码语言:javascript
复制
$output .= '<div class="staff-member">'

下面是您的代码的更新版本

代码语言:javascript
复制
function contact_profiles($args) 
{

    $output = "";

    $the_query = new WP_Query( $args );

    while ( $the_query->have_posts() ) : $the_query->the_post();

        $output .= '<div class="staff-member">'                             
        .'<a href="' . get_the_permalink() . '" title="Get in touch with ' . get_the_title() . '">' . get_the_post_thumbnail() . '</a>'
        .'<h2 class="name"><a href="' . get_the_permalink() . '" title="Get in touch with ' . get_the_title() . '">' . get_the_title() . '</a></h2>'
        .'<h3 class="job-role">' . get_post_meta( $post->ID, 'job_role', true ) . '</h3>'
        .'</div>';

    endwhile;

    wp_reset_postdata();

    return $output;
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30325170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档