サポート » 使い方全般 » 投稿保存時にカスタムフィールドから公開日時を指定する方法

  • いつも大変世話になっております。
    また壁にぶつかってココに来てしまいました。
    今回は少し複雑な状況です。

    add_action(‘save_post’ , ‘my_arrange_postname_postdate’); を使って、
    投稿保存時にカスタムフィールドから公開日時を取得して設定したいのですが、
    下記のコードだと、更新時には問題無く意図した公開日時になるのですが、
    新規投稿時には公開日時が投稿日時そのものになってしまいます。
    新規保存時の分岐処理の内容がおかしいとおもうのですが
    色んな方法を試しましたが上手く行きません。

    ちなみに、最初は

    add_filter( 'wp_insert_post_data'  , 'my_arrange_postname_postdate' , '99' , 2 );
    function my_arrange_postname_postdate( $data , $postarr ) {
    	//ここで$dataを上書きして、post_statusとpost_dateを設定
    	return $data;
    }

    で処理して、新規投稿時にも公開日時がきちんと上書きされていましたが、
    投稿がゴミ箱に捨てられなくなる等の弊害が出たため方針を変えました。

    以下、長いコードで大変恐縮ですが、ご指導、ご指南をいただければ幸いです。

    皆様、どうぞ宜しくお願いします。

    add_action('save_post' , 'my_arrange_postname_postdate');
    function my_arrange_postname_postdate ( $post_id ) {
    
    	if($_POST['post_type'] == 'hoge') {//対象は特定のカスタム投稿のみ
    
    		//自動保存なら無効
    		if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {return;}
    
    		//編集権限がなければ無効
    		if ( !current_user_can('edit_post', $post_id) ) {return;}
    
    		//新規保存かどうか(判定に問題無し)
    		if( !isset($_POST['post_name']) or $_POST['post_name']=="" ){
    			$flag_newpost = 1;
    		} 
    
    		//無限ループ対策
    		remove_action('save_post', 'my_arrange_title_postdate');
    
    		//準備(カスタム投稿を使用)
    		$my_post = array();
    		$my_post['post_type'] = 'hoge';
    
    		//カスタムフィールドの値を取得
    		//(下で使う$postname_from_customfield, $openday_from_customfieldを取得。問題無し。)
    
    		//公開日時をセット
    		$my_post['post_date'] = date('Y-m-d 00:00:00', strtotime($openday_from_customfield));
    		$my_post['post_date_gmt'] = date('Y-m-d H:i:s', strtotime($openday_from_customfield)-6*60*60);
    
    		//現時刻と公開日時を比較してpost_statusを決定(判定に問題無し)
    		if( strtotime($openday) > strtotime( date('Y-m-d') ) ) {
    			$my_post['post_status'] = "future";
    		} else {
    			$my_post['post_status'] = "publish";
    		}
    
    		//新規保存時(☆☆☆問題あり☆☆☆)
    		//↓これだとpost_statusのみfututeになり、公開日時が投稿日時そのものになる。
    		if ( $flag_newpost > 0 ){
    
    			//値だけ上書きして正規の保存ルートで保存
    			$_POST['post_status'] = $my_post['post_status'];
    			$_POST['hidden_post_status'] = $my_post['post_status'];
    			$_POST['post_name'] = $postname_from_customfield;
    			$_POST['post_date'] = $my_post['post_date'];
    			$_POST['post_date_gmt'] = $my_post['post_date_gmt'];
    
    		}
    		//更新時(問題無し)
    		else {
    
    			wp_update_post( $my_post );
    
    		}
    
    		//無限ループ対策解除
    		add_action('save_post', 'my_arrange_title_postdate');
    
    }
  • トピック「投稿保存時にカスタムフィールドから公開日時を指定する方法」には新たに返信することはできません。