Skip Navigation

[Résolu] Only Want Auto Numbering For New Post, Not When Editing The Post

Ce fil est résolu. Voici une description du problème et la solution proposée.

Problem: I would like to include a custom field value on my Project post type that begins at zero and is incremented for each new post. When I modify an existing post, I do not want the existing auto increment value to change.

Solution:
Use the "save_post" action to read the latest increment number, as well as any existing post increment number. If no increment number exists for the post, add to the latest increment number and insert that value in your custom field. If an increment number already exists, do not change it.

/* Auto number Project posts */
add_action( 'save_post', 'auto_number', 100, 3 );
function auto_number( $post_id, $post, $update ) {
    if ( $post->post_status == 'publish' && $post->post_type == 'project' ) {
        $project_args = array(
            'numberposts'       =>   2,
            'post_type'         =>   'project',
            'orderby'           =>   'post_date',
            'order'             =>   'DESC'
        );
        $projects = get_posts( $project_args );
         
        // don't update existing auto-numbering
        $this_id = get_post_meta( $projects[0]->ID, 'wpcf-project-number', true);
        if ( $this_id ) {
          return;
        }
 
        $last_id = get_post_meta( $projects[1]->ID, 'wpcf-project-number', true);
 
        if ( !$last_id ) {
            $last_id = 0;
        }
 
        $last_id++;
        update_post_meta( $post_id, 'wpcf-project-number', $last_id );
    }
}
This support ticket is created Il y a 6 années et 12 mois. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 6 réponses, has 2 voix.

Last updated by Team DNK Il y a 6 années et 12 mois.

Assisted by: Christian Cox.

Auteur
Publications
#515448

Hello Support... I found the below Thread which was extremely helpful in regards to setting up a way to auto number my custom post type Projects. All seems to be working good but I have noticed that when I update the post the number in my custom number field "project-number'"is reset based on last post thus throwing all numbering off.

BASED ON TOOLSET THREAD
https://toolset.com/forums/topic/auto-numbering-posts/

MY CODE

/* Auto number Project posts */
add_action( 'save_post', 'auto_number', 100, 3 );
function auto_number( $post_id, $post, $update ) {
    if ( $post->post_status == 'publish' && $post->post_type == 'project' ) {
        $project_args = array(
            'numberposts'       =>   2,
            'post_type'         =>   'project',
            'orderby'           =>   'post_date',
            'order'             =>   'DESC'
        );
        $projects = get_posts( $project_args );
        $last_id = get_post_meta( $projects[1]->ID, 'wpcf-project-number', true );

		if ( !$last_id ) {
			$last_id = 0;
		}
	
        $last_id++;
        update_post_meta( $post_id, 'wpcf-project-number', $last_id );
    }
}

PLEASE ADVISE
First - I want to confirm that this code is correctly written? In particular the part where I have inserted the check if there are no posts as the if statement uses curly brackets inside another if statement with it's own curly brackets?

Second - Could you assist me with fixing the code so that it does not reassign a new number when updating a post, only assigns the number when posts are created?

Kind Regards,
Dave

#515484

Hi you can try modifying the code as follows. Before updating, we look to see if the post already has a wpcf-project-number value. If so, we bail out of the update process. If not, we continue as usual.

/* Auto number Project posts */
add_action( 'save_post', 'auto_number', 100, 3 );
function auto_number( $post_id, $post, $update ) {
    if ( $post->post_status == 'publish' && $post->post_type == 'project' ) {
        $project_args = array(
            'numberposts'       =>   2,
            'post_type'         =>   'project',
            'orderby'           =>   'post_date',
            'order'             =>   'DESC'
        );
        $projects = get_posts( $project_args );
        
        // don't update existing auto-numbering
        $this_id = get_post_meta( $projects[0]->ID, 'wpcf-project-number', true);
        if ( $this_id ) {
          return;
        }

        $last_id = get_post_meta( $projects[1]->ID, 'wpcf-project-number', true);

        if ( !$last_id ) {
            $last_id = 0;
        }

        $last_id++;
        update_post_meta( $post_id, 'wpcf-project-number', $last_id );
    }
}
#515501

Hi Christian... Just gave it a go with the new section of code. While this prevents the post from being renumbered when editing, it also breaks auto numbering when creating a new post.

One further thing, I noticed that in my original code I am using "get_post_meta( $projects" should this use the singular "project" as this is the CPT slug name?

WORKS WITH THIS REMOVED

        // dont update existing auto-numbering
        $this_id = get_post_meta( $projects[0]->ID, 'wpcf-project-number', true);
        if ( $this_id ) {
          return;
        }
#515504

The name of the variable here shouldn't matter ($projects vs $project) as long as it's consistent throughout the function.

This code works in the setup I have here, but it's possible we're doing things differently. Can you tell me more about how your posts are initially created? Are you creating posts in the wp-admin area, or using a CRED form, or some other scripted way?

#515512
List of Project posts.png
Project post window.png

I am using a Types custom post type "Projects" and currently adding, updating and deleting Project posts from the WordPress admin area. I will be using CRED forms to manage all this from the front end as well, but not currently setup.

#515528

Okay, if you're storing the padded number with leading zeros, the function you have in place won't work because it increments the automatic numbering based on

$last_id++;

When you store padded values in the database, they are no longer interpreted as numbers, they are interpreted as strings. You can't increment a string like this without some type conversion. So you've got value type differences to consider. With that in mind, you must to decide what you want to save for these values. If you want to be able to use real numeric sorting, incrementing and comparisons of these values, you should not store the "padded" number. You should store the actual number, then use the shortcode from the other ticket to display the padded number on your site.

Once you store actual numbers, then the function you have already in place should work because it will be incrementing a number instead of incrementing a string. Search results can be sorted on the values, and filters can use the values for comparisons.

#515547

Thank You Christian... Given your helpful and informative explanation I have removed my original leading zero (padded values) solution from the other ticket and now the amended code you provided here seems to work great when I create a new Project post or edit an existing Project post.

Just in case someone else comes to this thread and wants to reference the other part of this topic here is the link to the related thread regarding leading zeros (padded values).

https://toolset.com/forums/topic/add-leading-zeros-to-number-field/#post-515532

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.