I want to have the excerpt of my custom post type 'Directory' to always have the default initial value of the shortcode:
[types field='dir_item_description'][/types]
(The contents of the Types custom field 'dir_item_description' is what I want automatically inserted in every excerpt for this custom post type so that is why I want to put the shortcode in the excerpt)
I'm just not sure what php code to use to accomplish this initialization in every new post (type='directory')?
Hello,
There isn't such a built-in feature within Toolset plugins.
Here are my suggestions:
1) When user edit/create a new post, you can use WordPress action hook save_post to trigger a PHP function
https://codex.wordpress.org/Plugin_API/Action_Reference/save_post
2) In this PHP function do these:
- Get the custom field 'dir_item_description' value
https://developer.wordpress.org/reference/functions/get_post_meta/
- Save it into post excerpt:
https://codex.wordpress.org/Function_Reference/wp_update_post
Thanks Luo, this definitely points me in the right direction. Do you recommend any examples for writing a function? This will be my first one. I’m quite excited. Many thanks for these tips.
Here is an example, I assume your custom field "dir_item_description" is created with Types plugin, you can put below PHP codes into your theme file "functions.php":
function my_excerpt_func( $post_id ) {
// If this is just a revision or not a directory post, don't do anything.
if ( get_post_type() != 'directory' || wp_is_post_revision( $post_id ) ) {
return;
}
remove_action('save_post', 'my_excerpt_func', 999);
// get the custom field dir_item_description value
$dir_item_description = get_post_meta( $post_id, 'wpcf-' . 'dir_item_description', true );
// Update excerpt
$arr = array(
'ID' => $post_id,
'post_excerpt' => $dir_item_description,
);
wp_update_post( $arr );
}
add_action( 'save_post', 'my_excerpt_func', 999 );
Please replace "directory" with your custom post type "Directory" slug
replace "dir_item_description" with your custom field "dir_item_description" slug
My issue is resolved now. Thank you! Worked like a charm!