Reputation: 85
I am making a counter where I can count amount of posts ever posted on my blog and save the value in a option.
I have created a function that gets executed every time I publish new post, but the issue I see is that the counter value increases by 2 even though I only publish 1 post which I only want it to increase by one.
Here is the function gets executed every time I publish a post
Here is the function gets executed every time I publish a post
function post_type_counter0() {
$number0 = get_option( 'wp_count_po0' );
$number0++;
update_option( 'wp_count_po0', $number0 );
}
And the function is hooked to the action
add_action( 'publish_post', 'post_type_counter0' );
I also tried to specify the value to be added to $number0 variable by doing this way
$number + 1;
But it still increased the value by 2 instead of 1.
Any idea??
Upvotes: 2
Views: 877
Reputation: 13840
I actually had a similar issue, and this is actually because the publish_post
hook can run more than once, which calls your function each and every time. The best way I found to avoid this was to add a meta field as a flag to each post.
add_action( 'publish_post', 'post_type_counter0', 10, 1 );
function post_type_counter0( $ID ){
$key = '_post_counted';
if( ! filter_var( get_post_meta( $ID, $key, true ), FILTER_VALIDATE_BOOLEAN ) ){
$number0 = get_option( 'wp_count_po0' );
if( update_option( 'wp_count_po0', ++$number0 ) )
update_post_meta( $ID, $key, true );
}
}
This function still gets hooked to the publish_post
hook, and passes along the $ID
of the post.
This lets you check to see if the meta field _post_counted
returns a truthy value. If it doesn't (returns an empty string because it doesn't exist), then it gets the total, updates the option (the ++
coming before the variable is the Pre-Increment operator, so it turns 7
to 8
before storing it). If the option was updated, then it adds the _post_counted
meta field to the post - meaning if the publish_post
hook ever runs again on that post, it will just skip over that block, resulting in it not changing.
This has the added benefit of not affecting the total post count when you draft a post to make changes and re-publish it later, or schedule it for posting. The save_post
hook is more notorious for running multiple times, but the publish_post
hook absolutely can depending on what your entire WP Environment looks like.
Upvotes: 1
Reputation: 905
You can use this instead:
$count_posts = wp_count_posts( 'jobs' )->publish;
Upvotes: 0