post meta - post_title in save_post action

admin2025-01-07  6

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.

Share Improve this question edited Jan 15, 2015 at 11:54 Giovanni Putignano asked Jan 15, 2015 at 9:58 Giovanni PutignanoGiovanni Putignano 3433 silver badges11 bronze badges 3
  • 1 false should be the right value. empty() returns false when your title is not empty. – Afterlame Commented Jan 15, 2015 at 10:53
  • Sorry I wrote wrong, I get true also if the title is not empty. – Giovanni Putignano Commented Jan 15, 2015 at 11:53
  • Could you post a little more code? – TheDeadMedic Commented Jan 15, 2015 at 16:33
Add a comment  | 

2 Answers 2

Reset to default 0

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
    }
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736260283a654.html

最新回复(0)