WordPress.org

Ready to get started?Download WordPress

Forums

Post meta not saving in save_post function (5 posts)

  1. cole20444
    Member
    Posted 1 year ago #

    Hey thanks ahead of time, here's my problem.

    Every time a post is updated i need to dynamically update or create a redirect for this post. I have the Quick Page/Post Redirect plugin installed which stores a post's redirect as 3 postmeta fields:

    _pprredirect_url,
    _pprredirect_type
    _pprredirect_active

    I thought this would be a simple task and below is the code i thought would do the trick:

    function post_redirect_create( $post_id ) {
    
    	global $wpdb;
    	//verify post is not a revision
    	$file = get_field('file', $_POST['post_ID']);
    	update_post_meta($_POST['post_ID'], _pprredirect_url, $file);
    	update_post_meta($_POST['post_ID'], _pprredirect_type, "301");
    	update_post_meta($_POST['post_ID'], _pprredirect_active, "1");
    }
    
    add_action( 'save_post', 'post_redirect_create' );

    Unfortunately this doesn't work. Nothing actually updates. I've verified that the correct data is getting to the update_post_meta function calls, by placing dumps and exit()'s. But the confusing part is if i add an exit() call at the very end, then the redirect gets updated in the database correctly. There must be something after this call that's either reverting what my function is doing, or there's a race condition of some kind and my code never executes.

    Thanks again ahead of time. I've been wrestling with this problem all day and would love some help with this.

  2. Brian Hogg
    Member
    Posted 1 year ago #

    Have you tried decreasing the priority so it executes later if something else is overwriting things? ie.

    add_action( 'save_post', 'post_redirect_create', 99 );

    Not that it should matter much to it saving but good to put quotes around the update meta functions:

    update_post_meta($_POST['post_ID'], '_pprredirect_url', $file);

  3. alieneila
    Member
    Posted 1 year ago #

    Also maybe try using $post_id instead of $_POST['post_ID']

  4. lekin
    Member
    Posted 1 year ago #

    hey cole,

    have you been able to resolve that issue? i'm experiencing the exact same thing. very frustrating!

    b.

  5. John
    Member
    Posted 7 months ago #

    I had the same issue and the decreasing the priority suggestion above fixed it. Thanks Brian!

Topic Closed

This topic has been closed to new replies.

About this Topic