Merge wp_get_post_terms

时间:2019-07-11 作者:Gamal Mohamed

我有这个密码

        while( $animes->have_posts() ) {
        $animes->the_post();
        $i++;
        $animeID[$i] = $post->ID;

        $args = array(
            \'orderby\' => \'meta_value_num\',
            \'order\' => \'DESC\',
            \'fields\' => \'all\',
            \'meta_query\' => [[\'key\' => \'episode_number\',\'type\' => \'NUMERIC\',]]
        );

        $episodes[$i] = wp_get_post_terms(intval( $animeID[$i] ), \'episodes\', $args );
        }
    }
我想将所有$集[$I]合并到一个数组中是否可能?

1 个回复
SO网友:Jacob Peattie

而不是放置wp_get_post_terms() 进入$episodes[$i], 您可以将其合并到$episodes 数组使用array_merge(), 像这样:

$episodes = []; // Initialise as an empty array first.

while( $animes->have_posts() ) {
    $animes->the_post();
    $animeID[] = get_the_ID();

    $args = array(
        \'orderby\'    => \'meta_value_num\',
        \'order\'      => \'DESC\',
        \'fields\'     => \'all\',
        \'meta_query\' => [
            [
                \'key\'  => \'episode_number\',
                \'type\' => \'NUMERIC\',
            ],
        ],
    );

    $episodes = array_merge( $episodes, wp_get_post_terms( get_the_ID(), \'episodes\', $args );
}
我还简化了代码,删除了不必要的$i 变量和使用get_the_ID() 获取当前帖子ID。

综上所述,如果您有一个帖子查询,并且希望获得该查询中帖子使用的术语,您可以通过一个帖子ID列表get_terms() 使用object_ids 参数:

$anime_ids = wp_list_pluck( $animes->posts, \'ID\' );
$episodes  = get_terms(
    \'object_ids\' => $anime_ids,
    \'meta_key\'   => \'episode_number\',
    \'orderby\'    => \'meta_value_num\',
    \'order\'      => \'DESC\',
);