• Resolved 0rca

    (@0rca)


    Hi all,
    I found a neat script that takes the date of a custom field and saves it as the post’s date:

    function change_post_date( $post_id, $post ) {
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
            return;
        if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
            return;
        if ( false !== wp_is_post_revision( $post_id ) )
            return;
        if ( ! current_user_can( 'edit_post', $post_id ) )
            return;
        $date_time_field = get_post_meta($post_id, 'datum', true);
        remove_action('save_post', 'change_post_date', 10);
        $args = array (
            'ID' => $post_id,
            'post_date' => $date_time_field,
            'post_date_gmt' => gmdate('Y-m-d H:i', $date_time_field )
        );
        wp_update_post( $args );
        add_action('save_post', 'change_post_date', 10);
    }
    add_filter('save_post', 'change_post_date', 10, 2);

    This works fine, but not in one go. The post date is saved before the custom field, so it would only use the newly entered date on a second save. This is logical, but is there a way around that? Can I save that specific custom date field before I call it via get_post_meta ?

    I am grateful for any input, since I am no “real” programmer ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Contributor dan.stefan

    (@danstefan)

    Hi 0rca,

    You could use a hook to save it as the pod is saved. Something like this for example, just replace podname with your custom pod type.

    add_filter( 'pods_api_pre_save_pod_item_podname', 'set_custom_date', 10, 2 );
    
    function set_custom_date( array $pieces, bool $is_new_item ): array {
    
    	// get field values: ok
    	$date = $pieces['fields']['custom_date']['value'];
    
    	if ( ! empty( $date ) ) {
    		if ( ! isset( $pieces['fields_active']['post_date'] ) ) {
    			$pieces['fields_active'][] = 'post_date';
    		}
    
    		//make sure that post_title is active
    		if ( ! isset( $pieces['fields_active']['post_date_gmt'] ) ) {
    			$pieces['fields_active'][] = 'post_date_gmt';
    		}
    
    		$pieces['object_fields']['post_date']['value']     = $date;
    		$pieces['object_fields']['post_date_gmt']['value'] = gmdate( 'Y-m-d H:i', strtotime( $date ) );
    
    	}
    
    	return $pieces;
    }
    
    Plugin Author Jory Hogeveen

    (@keraweb)

    Closing topic due to no reply, feel free to reopen if you still need help!

    Cheers, Jory

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Save custome field and use it as post date’ is closed to new replies.