【问题标题】:Getting list of all custom post type posts and regular posts from a certain category获取某个类别的所有自定义帖子类型帖子和常规帖子的列表
【发布时间】:2016-05-29 16:13:53
【问题描述】:

我正在尝试从名为社交的自定义帖子类型中获取所有个帖子的列表,社交类别中的任何普通帖子。我目前正在使用以下内容:

$posts = get_posts(
  array(
    'post_type' => array('social', 'post'),
    'category_name' => 'social',
    'post_status' => 'publish'
  )
);

这似乎只返回社交类别中的帖子,而不是社交帖子类型。无论如何都要返回两个 post_types?

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    生成的查询要求所有条件为真:post_typesocialpost AND category_namesocial AND post_statuspublish

    一个简单的解决方案是改用WP_Query

    $query = new WP_Query(array(
        'post_type' => array('social', 'post'),
        'category_name' => 'social',
        'post_status' => 'publish'
    ));
    $posts = $query->posts;
    

    然后,您可以使用posts_where 过滤器来修改查询的where 部分:

    add_filter( 'posts_where', 'my_posts_where', 10, 2 );
    function my_posts_where( $where, $query ) {
        ...modify $where...
        return $where;
    }
    

    我将跳过字符串操作部分,因为那里没有具体内容。无论如何,$where 看起来像这样(用我的 WordPress 安装测试):

    "AND ( wp_term_relationships.term_taxonomy_id IN (<number>))
    AND wp_posts.post_type IN ('social', 'post') AND 
    ((wp_posts.post_status = 'publish'))"
    

    你需要把它转换成这样的:

    "AND ( ((wp_term_relationships.term_taxonomy_id IN (<number>)
    AND wp_posts.post_type = 'post') OR (wp_posts.post_type = 'social'))
    AND (wp_posts.post_status = 'publish'))"
    

    最后,您需要确保my_posts_where 不会破坏其他查询。我可能只是在$query 对象中添加一些指示符,以在过滤器中识别此特定查询。

    【讨论】:

    • 正是我需要的!谢谢!
    猜你喜欢
    • 2015-10-11
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2014-07-10
    • 1970-01-01
    相关资源
    最近更新 更多