Skip to content

Instantly share code, notes, and snippets.

@coolamit
Created May 19, 2020 16:29
Show Gist options
  • Save coolamit/30b59dd2091eddf1671b1d90934b055a to your computer and use it in GitHub Desktop.
Save coolamit/30b59dd2091eddf1671b1d90934b055a to your computer and use it in GitHub Desktop.
Dummy post generation in WordPress for testing features.

How to use

The assumption here is that WordPress and WP_CLI are installed and configured already.

Though this script does not require WP_CLI and can be run using just PHP CLI, you would need to make sure you have proper DB connections in place and PHP objects in scope.

It is just easier to run this via WP_CLI as it takes care of loading the WordPress environment and having all WordPress vars and API accessible which this script needs to function.

It is not advised to run this via web-server/php-fpm in browser as the script could time out based on how many posts you want to generate.

fake-data.php

Set the $schema array as per the posts you want to generate.

WP-CLI command

wp --url=<SITE_URL> eval-file fake-data.php

Run this command. Make sure you are in same directory as fake-data.php.

<?php
/**
* Faker class to generate dummy posts in WordPress
*
* @author Amit Gupta <http://amitgupta.in/>
*
* @since 2019-11-28
*/
namespace iG\Inc\Utilities;
use \WP_Query;
use \WP_Term;
/**
* @codeCoverageIgnore
* @codingStandardsIgnoreFile
*/
class Faker {
const BATCH_SIZE = 20;
protected $_thumbnail_ids = null;
/**
* Class constructor
*/
public function __construct() {}
/**
* Factory method for the class to get a new instance.
*
* @return \iG\Inc\Utilities\Faker
*/
final public static function get_instance() : self {
$called_class = get_called_class();
$instance = new $called_class();
return $instance;
}
/**
* @param array $seeds
*
* @return mixed
*/
protected function _get_random_item( array $seeds ) {
$seeds = array_values( $seeds );
if ( empty( $seeds ) ) {
return false;
}
return mt_rand( 0, ( count( $seeds ) - 1 ) );
}
/**
* @param string $line
*
* @return void
*/
public function echo_line( string $line = '' ) : void {
echo $line;
echo PHP_EOL;
}
/**
* Method to get attachment IDs in an array
*
* @return array
*/
protected function _get_thumbnail_ids() : array {
if ( is_array( $this->_thumbnail_ids ) ) {
return $this->_thumbnail_ids;
}
$this->_thumbnail_ids = [];
$args = [
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => 10,
'suppress_filters' => false,
'orderby' => 'ID',
'order' => 'DESC',
];
$thumbnail_query = new WP_Query( $args );
if ( 0 < intval( $thumbnail_query->post_count ) ) {
$this->_thumbnail_ids = wp_list_pluck( $thumbnail_query->posts, 'ID' );
}
return $this->_thumbnail_ids;
}
/**
* @param array $term_slugs
* @param string $taxonomy
*
* @return array
*/
public function get_term_ids( array $term_slugs, string $taxonomy = 'category' ) : array {
if ( empty( $term_slugs ) ) {
return [];
}
$taxonomy = ( empty( $taxonomy ) ) ? 'category' : $taxonomy;
$term_ids = [];
foreach ( $term_slugs as $term_slug ) {
$term = get_term_by( 'slug', $term_slug, $taxonomy );
if ( is_a( $term, WP_Term::class ) ) {
$term_ids[] = $term->term_id;
}
unset( $term );
}
return $term_ids;
}
/**
* @return string
*/
public function get_random_paragraph() : string {
$seeds = [
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae dolor ut orci imperdiet ultrices.',
'Duis euismod massa sed nibh tempor, eu scelerisque dui euismod.',
'Suspendisse maximus turpis nec augue accumsan porttitor.',
'Duis eu tempus nibh. Morbi id tellus porta, faucibus felis vitae, volutpat arcu.',
'Curabitur eget est posuere, porttitor ante sed, faucibus felis.',
'Vestibulum rhoncus turpis id iaculis hendrerit. Vivamus sit amet velit eget augue hendrerit rhoncus non quis quam.',
'Pellentesque cursus ante sit amet purus suscipit, non ultrices eros sodales.',
'In quis varius metus, nec interdum neque.',
'Praesent at ultricies libero. Phasellus eget consequat nisl, et sollicitudin eros.',
'Mauris ac nisl gravida, condimentum nibh vitae, consectetur dui.',
'Donec rhoncus posuere quam at blandit. Maecenas id urna dolor.',
'Mauris magna quam, maximus ut ipsum vitae, tristique viverra tortor.',
'Morbi dapibus mi facilisis, accumsan neque quis, finibus lorem. Mauris tristique ut lectus at varius.',
'Nullam tincidunt eget turpis at venenatis. Donec bibendum iaculis erat, eget mollis elit ornare non.',
'Nunc rhoncus orci a dolor ultricies eleifend eu vel massa. Mauris id congue risus.',
'Maecenas quis feugiat ante, quis egestas ante. Etiam rhoncus est sit amet augue laoreet, in porta ipsum blandit.',
'Duis viverra enim nibh, sit amet cursus magna blandit bibendum.',
'Proin in lacus ut neque elementum mollis. Donec pharetra bibendum sem et porta. Phasellus nec mattis quam.',
'Sed id elit ut purus maximus sollicitudin at quis purus.',
'Nullam mollis urna non dui finibus, in eleifend tellus interdum. Aliquam vitae elit volutpat, fermentum enim ut, tristique lacus.',
];
$count = mt_rand( 4, 10 );
$paragraph = [];
for ( $i = 0; $i < $count; $i++ ) {
$sentence = $this->_get_random_item( $seeds );
$paragraph[] = $seeds[ $sentence ];
}
$paragraph = implode( ' ', $paragraph );
return $paragraph;
}
/**
* Method to set taxonomy terms on a post
*
* @param int $post_id
* @param array $taxonomy_terms
*/
protected function _set_terms( int $post_id, array $taxonomy_terms ) : void {
foreach ( $taxonomy_terms as $taxonomy => $term_slugs ) {
$terms = $this->get_term_ids( $term_slugs, $taxonomy );
wp_set_post_terms( $post_id, $terms, $taxonomy, false );
if ( 'category' === $taxonomy && 2 == count( $terms ) ) {
update_post_meta( $post_id, 'categories', (string) $terms[0] );
update_post_meta( $post_id, 'subcategories', (string) $terms[1] );
}
}
}
/**
* @param int $count
* @param array $thumbnails
* @param array $terms
* @param string $type
*
* @return void
*/
public function generate_posts( int $count = 1, array $thumbnails = [], array $terms = [], string $type = 'post' ) : void {
global $wpdb;
$count = ( 1 > $count ) ? 1 : $count;
$type = ( empty( $type ) ) ? 'post' : $type;
$thumbnails = array_values( $thumbnails );
$thumbnails = array_map( 'intval', $thumbnails );
$total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s", $type ) );
$this->echo_line( 'Starting generation of posts.' );
for ( $i = 0; $i < $count; $i++ ) {
$post_title = sprintf( '%s %d', get_post_type_object( $type )->labels->singular_name, ( $total + $i + 1 ) );
$args = [
'post_type' => $type,
'post_title' => $post_title,
'post_status' => 'publish',
'post_name' => sanitize_title( $post_title ),
'post_content' => $this->get_random_paragraph(),
];
$post_id = wp_insert_post( $args, true );
$this->echo_line( 'Post Added: ' . $post_title );
if ( ! is_wp_error( $post_id ) ) {
if ( ! empty( $terms ) ) {
$this->_set_terms( $post_id, $terms );
$this->echo_line( 'Terms added for Post: ' . $post_title );
}
if ( ! empty( $thumbnails ) ) {
$thumbnail_id = $this->_get_random_item( $thumbnails );
set_post_thumbnail( $post_id, $thumbnail_id );
unset( $thumbnail_id );
}
}
unset( $post_id, $args, $post_title );
if ( ( ( $i + 1 ) % self::BATCH_SIZE ) === 0 ) {
$this->echo_line( sprintf( '%d posts of type "%s" generated successfully', self::BATCH_SIZE, $type ) );
wp_cache_flush();
sleep( 2 );
}
} // end for loop
$this->echo_line( sprintf( 'Total %d posts of type "%s" generated successfully', $count, $type ) );
}
/**
* Method to generate posts in bulk based on a schema.
*
* Following is the structure of acceptable schema array.
*
* $schema = [
* [
* 'post_type' => 'post-type-1',
* 'count' => 10,
* 'terms' => [
* 'taxonomy-1' => [ 'term-1-slug' ],
* 'taxonomy-2' => [ 'term-2-slug', sub-term-2-slug ],
* ],
* ],
* ]
*
* @param array $schema
* @param array $thumbnails
*/
public function generate_posts_in_bulk( array $schema, array $thumbnails = [] ) : void {
if ( empty( $thumbnails ) ) {
$thumbnails = $this->_get_thumbnail_ids();
}
foreach ( $schema as $item ) {
$post_type = ( empty( $item['post_type'] ) ) ? '' : $item['post_type'];
$count = ( empty( $item['count'] ) ) ? 0 : intval( $item['count'] );
$count = ( 1 > $count ) ? 10 : $count;
$terms = ( empty( $item['terms'] ) ) ? [] : $item['terms'];
$this->generate_posts( $count, $thumbnails, $terms, $post_type );
}
}
} //end class
//EOF
<?php
require_once __DIR__ . '/class-faker.php';
$schema = [
[
'post_type' => 'post-type-a',
'count' => 10,
'terms' => [
'taxonomy-1' => [ 'term-1-slug' ],
'taxonomy-2' => [ 'term-2-slug', 'sub-term-2-slug' ],
],
],
];
\iG\Inc\Utilities\Faker::get_instance()->generate_posts_in_bulk( $schema );
//EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment