Home › Forums › Feature Requests › Allow setting a default value for Post Object fields › Reply To: Allow setting a default value for Post Object fields
I realize this is nearly a year later, but this is how I set a default.
The site I am working on has several custom post types that are being used for several things, three of which are “blogs”. There is another that is a ‘widget-post’ that is used for repeating items in different places, and it’s one of these I needed to include by default in my blogs.
I added a custom field to the widget-posts that allows one to be flagged as a default. I then set up the below function that will insert meta data via ‘save_post’, which is called upon when creating a new post. It will also retroactively save items that are edited.
/**
* Function will set the default Editorial Team description post if it isn't set at all
* This sets up the default upon creating a post
*
* @uses The $blog_post_types array, which has to have all of the blog post types listed in it
*/
function jp_blog_save_post( $post_id ) {
// get our post types
global $post_type, $blog_post_types;
// if it doesn't match, exit
if( ! in_array( $post_type, $blog_post_types ) )
return;
// get the meta data
$editorial_staff_post = get_post_meta( $post_id, 'editorial_staff_post', true );
// if it isn't set, set it
if( $editorial_staff_post == '' ) {
// set up args
$args = array(
'post_type' => 'widget-post',
'meta_key' => 'default_editorial_staff_description',
'meta_value' => 1,
);
// get the post(s) that have the checkbox checked
$wpost = get_posts( $args );
// set it as a default for this post
update_post_meta( $post_id, 'editorial_staff_post', $wpost[0]->ID );
}
}
add_action( 'save_post', 'jp_blog_save_post' );
Hope this helps anyone else that runs into this. I’m also sure it can be done with multiple choices.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.