I use save_post
action to save meta field and to check if post title is set. So I check the value returned by empty($post->post_title)
but I get true also if I set the title.
I use save_post
action to save meta field and to check if post title is set. So I check the value returned by empty($post->post_title)
but I get true also if I set the title.
Without knowing the surrounding code, it is hard to tell what the problem might be,
but you said you checked the $post
variable. Maybe the $post
variable is not set properly, the save_post
action only gives you the post id:
function get_post_title($post_id) {
$post = get_post($post_id);
if (empty($post->post_title)) {
// No title set, put in your code
}
}
add_action('save_post', 'get_post_title');
The save_post
action hook fires before post data is saved to the database at this point, the post title might not be set in the $post
object. Instead, you should use the $_POST
data directly to check if the title is set.
add_action('save_post', 'my_save_post_function');
function my_save_post_function($post_id) {
// Check if the post is being saved for the first time
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check if the post title is set in the $_POST data
if (isset($_POST['post_title']) && !empty($_POST['post_title'])) {
// The post title is set
// Perform your meta field saving logic here
} else {
// The post title is not set
// You can handle this case as needed
}
}
false
should be the right value.empty()
returnsfalse
when your title is not empty. – Afterlame Commented Jan 15, 2015 at 10:53