web-dev-qa-db-ja.com

カスタムフィールドが入力されていない場合に投稿が公開されないようにする

私はカスタム投稿タイプEventを持っています。それは開始と終了の日付/時刻カスタムフィールドを含みます(投稿編集画面のメタボックスとして)。

イベントデータが表示されているテンプレートで問題が発生するため(必要条件であるという事実以外に)、イベントが日付が入力されていないと発行(またはスケジュール)できないことを確認したいと思います。ただし、準備中に有効な日付が含まれていないドラフトイベントを開催できるようにしたいと思います。

チェックするためにsave_postをフックすることを考えていましたが、ステータス変更が起こらないようにするにはどうすればよいですか?

EDIT1: これは私がpost_metaを保存するために今使っているフックです。

// Save the Metabox Data
function ep_eventposts_save_meta( $post_id, $post ) {

if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    return;

if ( !isset( $_POST['ep_eventposts_nonce'] ) )
    return;

if ( !wp_verify_nonce( $_POST['ep_eventposts_nonce'], plugin_basename( __FILE__ ) ) )
    return;

// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ) )
    return;

// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though

//debug
//print_r($_POST);

$metabox_ids = array( '_start', '_end' );

foreach ($metabox_ids as $key ) {
    $events_meta[$key . '_date'] = $_POST[$key . '_date'];
    $events_meta[$key . '_time'] = $_POST[$key . '_time'];
    $events_meta[$key . '_timestamp'] = $events_meta[$key . '_date'] . ' ' . $events_meta[$key . '_time'];
}

$events_meta['_location'] = $_POST['_location'];

if (array_key_exists('_end_timestamp', $_POST))
    $events_meta['_all_day'] = $_POST['_all_day'];

// Add values of $events_meta as custom fields

foreach ( $events_meta as $key => $value ) { // Cycle through the $events_meta array!
    if ( $post->post_type == 'revision' ) return; // Don't store custom data twice
    $value = implode( ',', (array)$value ); // If $value is an array, make it a CSV (unlikely)
    if ( get_post_meta( $post->ID, $key, FALSE ) ) { // If the custom field already has a value
        update_post_meta( $post->ID, $key, $value );
    } else { // If the custom field doesn't have a value
        add_post_meta( $post->ID, $key, $value );
    }
    if ( !$value ) 
                delete_post_meta( $post->ID, $key ); // Delete if blank
}

}

add_action( 'save_post', 'ep_eventposts_save_meta', 1, 2 );

EDIT2: これは私がデータベースに保存した後に投稿データをチェックするために使用しようとしているものです。

add_action( 'save_post', 'ep_eventposts_check_meta', 99, 2 );
function ep_eventposts_check_meta( $post_id, $post ) {
//check that metadata is complete when a post is published
//print_r($_POST);

if ( $_POST['post_status'] == 'publish' ) {

    $custom = get_post_custom($post_id);

    //make sure both dates are filled
    if ( !array_key_exists('_start_timestamp', $custom ) || !array_key_exists('_end_timestamp', $custom )) {
        $post->post_status = 'draft';
        wp_update_post($post);

    }
    //make sure start < end
    elseif ( $custom['_start_timestamp'] > $custom['_end_timestamp'] ) {
        $post->post_status = 'draft';
        wp_update_post($post);
    }
    else {
        return;
    }
}
}

これに関する主な問題は、 別の質問save_postフック内でwp_update_post()を使用することで実際に記述されていた問題です。無限ループが発生します。

EDIT3: wp_insert_post_dataの代わりにsave_postをフックすることによってそれを行う方法を考え出しました。唯一の問題は、post_statusが元に戻されることですが、リダイレクトされたURLに&message=6を追加することによって、「Post published」という誤ったメッセージが表示されるようになりましたが、ステータスはDraftに設定されます。

add_filter( 'wp_insert_post_data', 'ep_eventposts_check_meta', 99, 2 );
function ep_eventposts_check_meta( $data, $postarr ) {
//check that metadata is complete when a post is published, otherwise revert to draft
if ( $data['post_type'] != 'event' ) {
    return $data;
}
if ( $postarr['post_status'] == 'publish' ) {
    $custom = get_post_custom($postarr['ID']);

    //make sure both dates are filled
    if ( !array_key_exists('_start_timestamp', $custom ) || !array_key_exists('_end_timestamp', $custom )) {
        $data['post_status'] = 'draft';
    }
    //make sure start < end
    elseif ( $custom['_start_timestamp'] > $custom['_end_timestamp'] ) {
        $data['post_status'] = 'draft';
    }
    //everything fine!
    else {
        return $data;
    }
}

return $data;
}
16
englebip

さて、これがようやく私がやることになったのです。チェックを行うPHP関数へのAjax呼び出し、 この回答 からインスパイアされたもの、そして_からの巧妙なヒントを使って 私がStackOverflowで尋ねた質問 。重要なのは、小切手を公開せずに公開したい場合にのみ、その小切手をいつでも小切手なしで保存できるようにすることです。これは実際には prevent 投稿の公開に対するより簡単な解決策であることになりました。それは他の誰かを助けるかもしれないので、私はそれをここに書きました。

まず、必要なJavascriptを追加してください。

//AJAX to validate event before publishing
//adapted from https://wordpress.stackexchange.com/questions/15546/dont-publish-custom-post-type-post-if-a-meta-data-field-isnt-valid
add_action('admin_enqueue_scripts-post.php', 'ep_load_jquery_js');   
add_action('admin_enqueue_scripts-post-new.php', 'ep_load_jquery_js');   
function ep_load_jquery_js(){
global $post;
if ( $post->post_type == 'event' ) {
    wp_enqueue_script('jquery');
}
}

add_action('admin_head-post.php','ep_publish_admin_hook');
add_action('admin_head-post-new.php','ep_publish_admin_hook');
function ep_publish_admin_hook(){
global $post;
if ( is_admin() && $post->post_type == 'event' ){
    ?>
    <script language="javascript" type="text/javascript">
        jQuery(document).ready(function() {
            jQuery('#publish').click(function() {
                if(jQuery(this).data("valid")) {
                    return true;
                }
                var form_data = jQuery('#post').serializeArray();
                var data = {
                    action: 'ep_pre_submit_validation',
                    security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
                    form_data: jQuery.param(form_data),
                };
                jQuery.post(ajaxurl, data, function(response) {
                    if (response.indexOf('true') > -1 || response == true) {
                        jQuery("#post").data("valid", true).submit();
                    } else {
                        alert("Error: " + response);
                        jQuery("#post").data("valid", false);

                    }
                    //hide loading icon, return Publish button to normal
                    jQuery('#ajax-loading').hide();
                    jQuery('#publish').removeClass('button-primary-disabled');
                    jQuery('#save-post').removeClass('button-disabled');
                });
                return false;
            });
        });
    </script>
    <?php
}
}

それから、チェックを処理する関数:

add_action('wp_ajax_ep_pre_submit_validation', 'ep_pre_submit_validation');
function ep_pre_submit_validation() {
//simple Security check
check_ajax_referer( 'pre_publish_validation', 'security' );

//convert the string of data received to an array
//from https://wordpress.stackexchange.com/a/26536/10406
parse_str( $_POST['form_data'], $vars );

//check that are actually trying to publish a post
if ( $vars['post_status'] == 'publish' || 
    (isset( $vars['original_publish'] ) && 
     in_array( $vars['original_publish'], array('Publish', 'Schedule', 'Update') ) ) ) {
    if ( empty( $vars['_start_date'] ) || empty( $vars['_end_date'] ) ) {
        _e('Both Start and End date need to be filled');
        die();
    }
    //make sure start < end
    elseif ( $vars['_start_date'] > $vars['_end_date'] ) {
        _e('Start date cannot be after End date');
        die();
    }
    //check time is also inputted in case of a non-all-day event
    elseif ( !isset($vars['_all_day'] ) ) {
        if ( empty($vars['_start_time'] ) || empty( $vars['_end_time'] ) ) {
            _e('Both Start time and End time need to be specified if the event is not an all-day event');
            die();              
        }
        elseif ( strtotime( $vars['_start_date']. ' ' .$vars['_start_time'] ) > strtotime( $vars['_end_date']. ' ' .$vars['_end_time'] ) ) {
            _e('Start date/time cannot be after End date/time');
            die();
        }
    }
}

//everything ok, allow submission
echo 'true';
die();
}

この関数は、すべて問題なければtrueを返し、通常のチャンネルで投稿を公開するためのフォームを送信します。そうでない場合、関数はalert()として表示されるエラーメッセージを返し、フォームは送信されません。

9
englebip

M0r7if3rが指摘したように、save_postフックを使用して投稿を公開することを防止する方法はありません。フックが起動される時点までに、投稿は既に保存されているためです。ただし、次のコードを使用すると、wp_insert_post_dataを使用せずに無限ループを発生させることなくステータスを元に戻すことができます。

以下はテストされていませんが、動作するはずです

<?php
add_action('save_post', 'my_save_post');
function my_save_post($post_id) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
         return;

    if ( !isset( $_POST['ep_eventposts_nonce'] ) )
         return;

    if ( !wp_verify_nonce( $_POST['ep_eventposts_nonce'], plugin_basename( __FILE__ ) ) )
         return;

    // Is the user allowed to edit the post or page?
     if ( !current_user_can( 'edit_post', $post->ID ) )
         return;

   // Now perform checks to validate your data. 
   // Note custom fields (different from data in custom metaboxes!) 
   // will already have been saved.
    $prevent_publish= false;//Set to true if data was invalid.
    if ($prevent_publish) {
        // unhook this function to prevent indefinite loop
        remove_action('save_post', 'my_save_post');

        // update the post to change post status
        wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));

        // re-hook this function again
        add_action('save_post', 'my_save_post');
    }
}
?>

確認していませんが、コードを見ると、フィードバックメッセージに投稿が公開されたという誤ったメッセージが表示されます。これは、WordPressがmessage変数が正しくないURLにリダイレクトするためです。

それを変更するために、redirect_post_locationフィルタを使うことができます。

add_filter('redirect_post_location','my_redirect_location',10,2);
function my_redirect_location($location,$post_id){
    //If post was published...
    if (isset($_POST['publish'])){
        //obtain current post status
        $status = get_post_status( $post_id );

        //The post was 'published', but if it is still a draft, display draft message (10).
        if($status=='draft')
            $location = add_query_arg('message', 10, $location);
    }

    return $location;
}

上記のリダイレクトフィルタを要約すると:投稿が公開されるように設定されていてもそれでもドラフトである場合は、それに応じてメッセージを変更します(これはmessage=10です)。繰り返しますが、これはテストされていませんが、動作するはずです。 add_query_arg のコーデックスは、変数がすでに設定されている場合、それを置き換える関数であることを示唆しています(しかし、私が言うように、私はこれをテストしていません)。

14
Stephen Harris

私はこれについて取り組むための最善の方法はそれがそうであればそれを元に戻すことであるのでそれほど状況の変化が起こるのを防ぐことではないと思います。たとえば、非常に高い優先順位で(save_postをフックして(つまり、メタ挿入を行った後に)起動し、保存されたばかりの投稿のpost_statusを確認して、保留に更新しますそれがあなたの基準を満たしていない場合はドラフトまたは何でも)。

別の方法はpost_statusを直接設定するためにwp_insert_post_dataをフックすることです。この方法の欠点は、私の知る限りでは、まだpostmetaをデータベースに挿入していないため、チェックを行うためにそれを処理するなどしてから挿入するために再度処理する必要があることです。それをデータベースに入れます...これはパフォーマンスやコードの面で大きなオーバーヘッドになる可能性があります。

3
mor7ifer

最善の方法は、JAVASCRIPTです。

<script type="text/javascript">
var field_id =  "My_field_div__ID";    // <----------------- CHANGE THIS

var SubmitButton = document.getElementById("save-post") || false;
var PublishButton = document.getElementById("publish")  || false; 
if (SubmitButton)   {SubmitButton.addEventListener("click", SubmCLICKED, false);}
if (PublishButton)  {PublishButton.addEventListener("click", SubmCLICKED, false);}
function SubmCLICKED(e){   
  var passed= false;
  if(!document.getElementById(field_id)) { alert("I cant find that field ID !!"); }
  else {
      var Enabled_Disabled= document.getElementById(field_id).value;
      if (Enabled_Disabled == "" ) { alert("Field is Empty");   }  else{passed=true;}
  }
  if (!passed) { e.preventDefault();  return false;  }
}
</script>
0
T.Todua