I’m looking for the snippet code to allow me to automatically insert the post_id for each new post in wordpress (CPT "property")
the reason: I have several posts with the same style of title like
"hello world" for example
if I have 10 posts with hello world .. how to differentiate them in the post_title?
I don’t know if this kind of code snippet exists
but it will save me a lot of time to copy / paste
"hello world – id 2140"
"hello world – id 2141"
"hello world – id 2142"
new post >
(your post name here) – id 2143
if you have an idea please share
EDIT :
I found this post which talks about the same thing.
it seems like it’s…not really possible
because post_id is generated when I click on publish
how could it display an id to a new post when it’s not yet generated?
I think I will still have long copy/paste days to come…
3
Answers
You can do it with a simple sql:
To display the ID after the title of each post you can edit the templates of your theme, for example the
index.php
file, thesingle.php
file,page.php
etc. and addecho get_the_ID();
right afterthe_title()
in the PHP code of those templates.BTW: I’d create a child theme in this case because any theme update will overwrite those template files. (see https://developer.wordpress.org/themes/advanced-topics/child-themes/ for more on that subject)
You’re probably looking for some function hooked to
save_post
.As of WP 3.7, an alternative to the
save_post
action has been introduced, which is called for specific post types:save_post_{post_type}
. In your case we can use thesave_post_property
hook to intercept the post title and apply changes to it (where property refers to the dynamic part_{post_type}
).Hooking to this action prevents your callback to be unnecessarily triggered. It fires once a post has been saved (like
save_post
).We need to discard any updates, autosaves or revisions actions. The WordPress autosave system fire every 60 seconds.
The
$update
parameter fromsave_post_{post_type}
is supposed to determined whether this is an existing post being updated. It applies more specifically to a post autosave revision. The$update
parameter will always be true when firing throughwp_publish_post
. But that isn’t true for its usage inwp_insert_post
.In our case, the
wp_publish_post
function publish a post by transitioning the post status.By additionally crosschecking the post status we can effectively determine whether it is indeed a non-existing post.
A few more things: If you are calling a function such as
wp_update_post
that includes thesave_post
hook, your hooked function will create an infinite loop. To avoid this, unhook your function before calling the function you need, then re-hook it afterward.save_post_{post_type}
will fire on postupdate
(eg: autosave) orpublish
which is why we’re running into an infinite loop.