0

In term of building demo content, I would like to ask is there any way so that I can set my posts to have random categories and tags. These posts, categories, and tags are already existing in Dashboard. I would like to ignore the solution of import dummy demo data from the other sources. Thanks

1 Answer 1

0

Oh, I made it myself.

Just run this function until you satisfy

function Trang_Mix_CatesTags() {
$cats = get_categories(array(
    'hide_empty' => false,
));
$query = new WP_Query('post_type=post&posts_per_page=-1&post_status=publish');
if( $query->have_posts() ):
    while($query->have_posts()): $query->the_post();
        $numbers = range(0, (count($cats)-1));
        shuffle($numbers);
        $r = array_slice($numbers, 0, 5);
        $c = array(
            $cats[$r[0]]->term_id,
            $cats[$r[1]]->term_id,
            $cats[$r[2]]->term_id,
            $cats[$r[3]]->term_id,
            $cats[$r[4]]->term_id
        );
        wp_set_post_categories( get_the_ID(), $c );
    endwhile;
endif;
wp_reset_postdata();

$tags = get_categories(array(
    'taxonomy' => 'post_tag',
    'hide_empty' => false,
));
$query = new WP_Query('post_type=post&posts_per_page=-1&post_status=publish');
if( $query->have_posts() ):
    while($query->have_posts()): $query->the_post();
        $numbers = range(0, (count($tags)-1));
        shuffle($numbers);
        $r = array_slice($numbers, 0, 5);
        $c = array(
            $tags[$r[0]]->term_id,
            $tags[$r[1]]->term_id,
            $tags[$r[2]]->term_id,
            $tags[$r[3]]->term_id,
            $tags[$r[4]]->term_id
        );
        wp_set_post_tags( get_the_ID(), $c );
    endwhile;
endif;
wp_reset_postdata();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.