yuheijotaki.com

wp-load.php を使って記事を自動更新

<?php

////////////////////////////////////
// wp-load.php を使って記事を自動更新
// 参考:http://liginc.co.jp/web/wp/customize/158083/
////////////////////////////////////
// 手順
// 1.下記のphpを編集し更新箇所の調整
// 2.このファイルを /wordpress/ フォルダ直下にアップロード
// 3.アップロードしたURLにアクセスし更新
// 4.完了したらサーバー上から削除
////////////////////////////////////

require_once( dirname(__FILE__).'/wp-load.php' ); // wp-load.php を読み込み

// 更新記事の設定をget_postsで行う
$args = array(
	'post_status' => 'publish',
	'post_type' => 'post',
	'posts_per_page' => -1,
	// 'p' => '9999' // テスト用
);
$posts = get_posts($args);
foreach ( $posts as $post ) {

	/////////////////////
	// 投稿カスタムフィールド
	/////////////////////
	// コメントの取得
	$args = array(
		'status'  => array('approve','hold'),
		'post_id' => $post->ID,
		'number'  => 1, // 最新の1件のみ
		'order' => 'desc' // 新しい順
	);
	$comments = get_comments( $args );
	if ( $comments ) {
		// コメントがある場合 'custom_date' というカスタムフィールドに最新コメントの日付をUNIX形式で格納する
		foreach ( $comments as $comment ) {
			$comment_id = get_comment_ID(); // このコメントIDを取得
			$comment_date = get_comment_date( 'Y/m/d H:i:s', $comment_id );  // このコメントの日付を取得
			$comment_date = strtotime( $comment_date );  // UNIX TIMESTAMP として取得
			update_post_meta($post->ID, 'custom_date', $comment_date); // カスタムフィールドに日付を追加
		}
	} else {
		// コメントがない場合 'custom_date' というカスタムフィールドに投稿の日付をUNIX形式で格納する
		$post_date = get_the_date( 'Y/m/d H:i:s', $post->ID ); // get_the_date()でこの投稿の日時を取得
		$post_date = strtotime( $post_date ); // UNIX TIMESTAMP として取得
		update_post_meta($post->ID, 'custom_date', $post_date); // カスタムフィールドに日付を追加
	}

	////////////////////////////////////
	// 投稿一般情報関連(タイトル/コンテンツなど)
	////////////////////////////////////
	// $my_post = array(
		// 'post_title'   => '投稿のタイトルです',
		// 'post_content' => '投稿のコンテンツです',
	// );
	// wp_update_post( $my_post );

}

?>