WordPressで公開済みの記事を指定した日時で更新する方法
- : WordPress
- : functions.php
- :
すでに公開済みの記事を指定した日時で更新したいという場合、Wordpressでは出来ないかと思いってましたが方法ありました。ありがとうございます。
テーマをカスタマイズするとダッシュボードの編集ページに「更新予定日時の指定」の項目が表示されますので、更新したい日時を入力し更新すると入力した時間になると更新されるようになりました。 日時を変更しない場合はすぐに更新されます。
ただこの方法だとテーマの本文のところを「the_content();」から「echo my_get_content();」に変更する必要が有るため、リッチエディタで改行プラグインなど使っている場合は挙動がおかしくなりましたが、出来ないよりは良いです。
「更新予定日時の指定」をしたいテーマ「the_content();」を置換える
<?php echo my_get_content(); ?>
functions.phpに追加
date_default_timezone_set('Asia/Tokyo'); $fu_key = 'futureupdate'; function my_get_content(){ global $post, $fu_key; $now = date('Y/m/d H:i'); $update = get_post_meta($post->ID, $fu_key, true); if(!$update || ($update && $update <= $now)) return get_the_content(); $args = array( 'order' => 'DESC', 'orderby' => 'ID', 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit', 'meta_key' => $fu_key, 'meta_value' => $now, 'meta_compare' => '<=' ); if($revisions = get_children($args)) foreach($revisions as $revision) return $revision->post_content; return 'No content.'; } //meta_box追加 function my_meta_futureupdate_box(){ add_meta_box('my_meta_futureupdate_box', '更新予定日時の指定', 'my_meta_futureupdate_html', 'post', 'normal', 'high'); add_meta_box('my_meta_futureupdate_box', '更新予定日時の指定', 'my_meta_futureupdate_html', 'page', 'normal', 'high'); } function my_meta_futureupdate_html($post, $box){ global $fu_key; $value = get_post_meta($post->ID, $fu_key, true); if(!$value) $value = ''; echo '<input type="hidden" name="my_meta_futureupdate_nonce" id="my_meta_futureupdate_nonce" value="'.wp_create_nonce(get_bloginfo('template_url') . $fu_key).'" />'."\n" . '<div><label for="futureupdate">更新予定日時(YYYY/MM/DD HH:II)</label>'."\n" . '<input type="text" name="futureupdate" value="'. $value .'" size="50" /></div>'."\n"; } function my_meta_futureupdate_update($post_id){ global $fu_key; if(!wp_verify_nonce( $_POST['my_meta_futureupdate_nonce'], get_bloginfo('template_url') . $fu_key)){ return $post_id; } if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id; if('page' == $_POST['post_type']){ if(!current_user_can('edit_page', $post_id)) return $post_id; }else{ if(!current_user_can('edit_post', $post_id)) return $post_id; } if($parent_id = wp_is_post_revision($post_id)){ $old = get_post_meta($parent_id, $fu_key, true); if($old) update_metadata('post', $post_id, $fu_key, $old); }else{ if(isset($_POST[$fu_key])) update_metadata('post', $post_id, $fu_key, $_POST[$fu_key]); } } add_action('admin_menu', 'my_meta_futureupdate_box'); add_action('save_post', 'my_meta_futureupdate_update');