Skip to content

Instantly share code, notes, and snippets.

@torounit
Last active December 17, 2015 19:39
Show Gist options
  • Save torounit/5662365 to your computer and use it in GitHub Desktop.
Save torounit/5662365 to your computer and use it in GitHub Desktop.
カスタムフィールドで指定した時間にカテゴリー(or タグ or カスタム分類のターム)を切り替えるクラス。Advanced Custom Fieldsに依存。
<?php
Class Scheduled_Term {
public $taxonomy = "category";
public $term_id = 1;
public $term_slug;
public $event_key = "scheduled_term";
public $date_key = 'date';
public $time_key = 'time';
public $post_id;
public $date_time_key = "";
public function init() {
add_action('edit_post', array(&$this, "scheduled_event_fire") );
add_action( $this->event_key, array(&$this, "set_term") );
}
public function scheduled_event_fire( $post_id ) {
$this->post_id = $post_id;
add_action('shutdown', array(&$this, "scheduled_event") );
}
protected function get_acf_meta( $post_id, $key ) {
$acf_field = get_field_object( $key );
$acf_key = $acf_field["key"];
if(isset( $_POST["fields"][$acf_key]) ) {
return $_POST["fields"][$acf_key];
}
else {
return get_post_meta( $post_id, $key, 1 );
}
return false;
}
public function scheduled_event() {
$post_id = $this->post_id;
$post = get_post( $this->post_id );
if( $this->date_time_key ) {
$datetime = $this->get_acf_meta( $this->post_id, $this->date_time_key );
}else {
$date = $this->get_acf_meta( $this->post_id, $this->date_key );
$time = " ".$this->get_acf_meta( $this->post_id, $this->time_key );
$datetime = $date.$time;
}
wp_clear_scheduled_hook( $this->event_key, array( $post->ID ) ); //イベントの初期化
$timestamp = strtotime( $datetime );
$gmt = $timestamp - 9*60*60;
if( $gmt ) {
wp_schedule_single_event( $gmt, $this->event_key, array( $post->ID ,$date.$time)); //イベントのセット
}
}
public function set_term( $post_id, $str = "" ) {
if( $this->term_slug ) {
$term = get_term_by( "slug", $this->term_slug, $this->taxonomy );
$this->term_id = $term->term_id;
$this->term_id = intval( $this->term_id );
}
wp_set_object_terms( $post_id, $this->term_id, $this->taxonomy );
}
}
<?php
/*
Advanced Custom Fieldsで作ったフィールドを使うことが前提。
get_acf_metaがACFに依存しているので、それをオーバーライドすれば、ACF以外でも動作します。
*/
//インスタンス化
$scheduled_term = new Scheduled_Term;
//指定した時間にカテゴリーをopenに変更
$scheduled_term->term_slug = "open";
//指定した時間にカテゴリーIDで指定
$scheduled_term->term_id = "10";
//term_idよりslugの方が優先的に使われる
$scheduled_term->term_id = "10";
$scheduled_term->term_slug = "open";
//タクソノミーを指定
$scheduled_term->taxonomy = "status";
$scheduled_term->term_slug = "closed";
//カスタムフィールドのキーを変更
$scheduled_term->date_key = "date";
$scheduled_term->time_key = "time";
//date_time_keyを指定した場合、time_keyとdate_keyは無視される。
$scheduled_term->date_time_key = "datetime";
//複数のイベントを発生させるときはevent_keyを変更
$scheduled_term->event_key = "event_2"
$scheduled_term->init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment