Skip to content

Instantly share code, notes, and snippets.

@YuzuruSano
Last active September 8, 2018 00:17
Show Gist options
  • Select an option

  • Save YuzuruSano/ffef72baba78980a524d1c3cf42a0f05 to your computer and use it in GitHub Desktop.

Select an option

Save YuzuruSano/ffef72baba78980a524d1c3cf42a0f05 to your computer and use it in GitHub Desktop.
[Wordpress] 投稿タイプ、タクソノミ、件数指定して大量のテスト用投稿をinsertする
<?php
class hytInsertMockPosts {
public function __construct($post_type = 'post',$taxonomies = ['category'],$num = 10){
$this->post_type = $post_type;
$this->taxonomies = $taxonomies;
$this->num = $num;
}
public function mbRange($start, $end){
if ($start == $end) {
return array($start);
}
$_result = array();
list(, $_start, $_end) = unpack("N*", mb_convert_encoding($start . $end, "UTF-32BE", "UTF-8"));
$_offset = $_start < $_end ? 1 : -1;
$_current = $_start;
while ($_current != $_end) {
$_result[] = mb_convert_encoding(pack("N*", $_current), "UTF-8", "UTF-32BE");
$_current += $_offset;
}
$_result[] = $end;
return $_result;
}
public function makeRandStr($length) {
$str = array_merge(range('a', 'z'), range('0', '9'), range('A', 'Z'), $this->mbRange('あ', 'ん'));
$r_str = null;
for ($i = 0; $i < $length; $i++) {
$r_str .= $str[rand(0, count($str) - 1)];
}
return $r_str;
}
private function getRelateTerms(){
$relate_taxonomies = [];
foreach($this->taxonomies as $tax){
$targets = get_terms($tax,[ 'hide_empty' => false]);
foreach($targets as $target){
$relate_taxonomies[$tax][] = $target->term_id;
}
}
return $relate_taxonomies;
}
public function insertMock(){
$taxes = $this->taxonomies;
$relate_taxonomies = $this->getRelateTerms();
foreach($taxes as $tax){
$targets = get_terms($tax,[ 'hide_empty' => false]);
foreach($targets as $target){
$relate_taxonomies[$tax][] = $target->term_id;
}
}
for($i=0;$i<$this->num;$i++){
$post = [
'post_title'=>$this->makeRandStr(30),
'post_content'=>$this->makeRandStr(400),
'post_type' => $this->post_type,
'post_status' => 'publish'
];
$newpost = wp_insert_post($post,true);
foreach($taxes as $tax){
shuffle($relate_taxonomies[$tax]);
$end = (count($relate_taxonomies[$tax]) > 3) ? 3 : max($relate_taxonomies[$tax]);
$offset = rand(1,$end);
$r_taxes = array_slice($relate_taxonomies[$tax],0,$offset);
wp_set_object_terms($newpost,$r_taxes,$tax);
}
}
}
}
//example
require_once('{path}hytInsertMockPosts.php');
function insertMock(){
$mock = new hytInsertMockPosts('facilities',['genre','place1','place2'],300);
$mock->insertMock();
}
add_action( 'wp_head', 'insertMock', 9999 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment