Search code examples
wordpresspermalinksquery-variables

Unable to save Query Vars with a post


I'm trying to save Query Vars to a post for later retrieval.

I'm using permalinks in this format: domain.com/%category%/%postname%/

Example:

  1. I create a following page

    domain.com/page-003/
    
  2. I add Query Var called email to the page

    add_query_arg('email', 'test@abc.com', 'domain.com/page-003/')
    
  3. Now when I call

    get_permalink($post_id);
    

    I get

    domain.com/page-003/
    

    Instead of

    domain.com/page-003/?email=test@abc.com
    

What am I missing? Aren't Query Vars saved with a post?


Solution

  • You want to save some meta data which you want to restore later on and add as query arg into the URL.

    You need to first save it as post_meta like e.g. when you save post with that data. You use:

    <?php update_post_meta(get_the_ID(), 'email_address', 'abc@mail.com'); ?>
    

    More details: https://codex.wordpress.org/Function_Reference/update_post_meta

    Then during the retrieval, you may hook into a HOOK early on like template_redirect or earlier of the post you can get post_meta to get the email and then add to query arg:

    <?php $email = get_post_meta( get_the_ID(), 'email_address' ); ?>
    

    Then

    esc_url( add_query_arg( 'email', $email, get_permalink( get_the_ID() ) ) );
    

    Something like that, code is untested, I just wrote here, you may please read detailed doc in codex for each function used above.

    Update: How to update/fill Ninja form field from Meta Value:

    add_filter( 'ninja_forms_render_default_value', 'wm_the_value' , 10 , 3);
    
    function wm_the_value( $default_value, $field_type, $field_settings ) {
        if( 'textbox' == $field_type && in_array('ref' , $field_settings)){
            $default_value = get_post_meta(get_the_ID(),'_listing_mls', true);
        }
    
        return $default_value;
    }
    

    'ref' is field name in Ninja form. '_listing_mls' is meta_key name from WP database.

    Hope it works for you.