Execute wp_after_insert_post after the permalink is customized

To execute update_post_meta after the permalink is customized, you can use the save_post hook instead of wp_after_insert_post. Here’s how you can modify your code:

add_action('save_post', 'add_permalink_to_new_post', 10, 2);

function add_permalink_to_new_post($post_id, $post) {

    // Check if this is a new post
    if ($post->post_date_gmt == $post->post_modified_gmt) {
        // Only run this on a newly created post
        update_post_meta($post_id, 'canonical_permalink', get_permalink($post_id));
    }
}

In the updated code:

  1. I’ve changed the hook to save_post, which fires after a post is saved or updated.
  2. Inside the add_permalink_to_new_post function, we check if the post_date_gmt and post_modified_gmt are the same. If they are, it means that the post is newly created, as the modification date hasn’t been updated yet.
  3. If it’s a newly created post, we update the canonical_permalink post meta with the customized permalink using get_permalink($post_id).

This way, the update_post_meta function will only be called after the permalink is customized for a newly created post, ensuring that you get the permalink you want without any issues with ?p=[ID]. You can now use this updated code in your WordPress theme or plugin to achieve the desired functionality.