Search
Close this search box.

wordpress站群主站向子站分发文章 代码

Details

<?php
$current_blog_id = get_current_blog_id();
$log_file = 'log/sql.log'; // 日志文件路径
wp_reset_query();
// print_r("<pre>");
// print_r($current_blog_id);
//获取主站十条内容,以分配到子站
$args = array(
    'posts_per_page'  => 10, //需要提取的文章数
    'post_type'       => 'post',
	'orderby'=>'date',
	'order'=>'DESC',
	'category__in' => array( 16 ), 
    'post_status'     => 'publish', //文章状态
	'meta_query'      => array(
		'relation' => 'OR', 
		array(
			'key' => 'artme', // 自定义字段名称
            'compare' => 'NOT EXISTS' // 筛选出该自定义字段不存在的文章
		)
	)
);

$posts_ten_art = new WP_Query($args);

$posts_ten = $posts_ten_art->posts;

foreach ($posts_ten as $t){
    $t->meta = get_post_meta($t->ID,'artme',true);
}
//获取所有子站列表
$blogList = get_blog_list(0, 'all');
print_r("<pre>");
print_r($blogList);
if (count($posts_ten) > 0) {
    foreach ($posts_ten as $val){
        //随机获取子站
        $mt_rands = mt_rand(0,count($blogList)-1);
        //随机分配子站BLOG_ID
        $ablogids_is = $blogList[$mt_rands]['blog_id'];
        print_r("<pre>");
        print_r($mt_rands . '----' . $ablogids_is);
        // 切换到子站点
        switch_to_blog($ablogids_is);
        print_r("<pre>");
        print_r(get_current_blog_id());
        //找出所有栏目
        $cate = get_terms(array(
            'taxonomy' => 'category',
            'hide_empty' => false,
        ));
        $mt_cate_rands = mt_rand(0,(count($cate)-2));
        $mt_cate_rands_id = $cate[$mt_cate_rands]->term_id;
        $post_arr = array(
            'post_author'  => 1,
            'post_title' => $val->post_title,
            'post_content' => $val->post_content,
            'post_status' => 'publish',
            'post_type' => 'post',
            'post_category' => array($mt_cate_rands_id)
        );
        $result = wp_insert_post($post_arr);
        print_r("<pre>");
        print_r($result . 'qqqqqqqqqqq');
        // 恢复当前站点
        //switch_to_blog(1);
        restore_current_blog();
        // print_r("<pre>");
        // print_r(get_current_blog_id());
        if($result){
            add_post_meta($val->ID, 'artme', '2');
            print_r(get_post_meta($val->ID, 'artme',true) . 'ppppppppppp');
             $log_message = date('Y-m-d H:i:s') . '----------' . $val->post_title . "\n";
                // 写入日志文件
             file_put_contents($log_file, $log_message, FILE_APPEND);
             echo "新增数据" . PHP_EOL;
        }
    }
}

?>

发表评论

Optimized by WPJAM Basic