Viewing 1 replies (of 1 total)
  • Hi,

    I have implemented this on a custom post type called section. Maybe the author could take the best of it for a core integration. Note that I was using it inside a class.

    The bea_add_order fires on transition_status :

    add_action( 'transition_post_status', [ $this, 'bea_add_order' ], 10, 3 );
    /**
    	 * Manage to add the section order (post_order)
    	 * Value will be max published ones + 1
    	 *
    	 * @param $new_status
    	 * @param $old_status
    	 * @param $post
    	 *
    	 * @return bool|\WP_Error
    	 * @author Maxime CULEA
    	 */
    	public function add_order( $new_status, $old_status, $post ) {
    		/**
    		 * Fires on :
    		 * - section post type
    		 * - if not the same post status. Typically, on update it will be new_status = publish & old_status = publish
    		 * - if new post status is not publish
    		 */
    		if ( BEA_CPT_SECTION_NAME !== $post->post_type || $new_status === $old_status || 'publish' !== $new_status ) {
    			return false;
    		}
    
    		$found_posts = wp_count_posts( BEA_CPT_SECTION_NAME );
    		if ( empty( $found_posts ) || ! isset( $found_posts->publish ) ) {
    			return false;
    		}
    
    		/**
    		 * Set post's menu order to the total found published sections  - 1
    		 * While the current one, is already published
    		 */
    		$order = $found_posts->publish - 1;
    		$update = wp_update_post( [ 'ID' => $post->ID, 'menu_order' => $order <= 0 ? 0 : $order ] );
    		return is_wp_error( $update ) ? $update : true;
    	}

    Best !

Viewing 1 replies (of 1 total)
  • The topic ‘Update menu order when new post is created’ is closed to new replies.