Viewing 1 replies (of 1 total)
  • sanderjansma,
    I just saw this was unanswered – sorry.

    There is no shortcut for adding redirects, but you can add meta with normal WordPress meta functions. There are 3 meta keys you need to use when you do it:

    _pprredirect_active
    _pprredirect_type
    _pprredirect_url

    You just set them as you would add meta to a post –

    update_post_meta($post->ID,'_pprredirect_active', '1');
    update_post_meta($post->ID,'_pprredirect_type', '301');
    update_post_meta($post->ID,'_pprredirect_url', 'http://someurl.com/');

    So I guess if you wanted to, you could add a function of your own to be a shortcut (add to functions.php):

    function set_redirect($postid = 0, $type = '301', $url = '', $active = 1){
        // if user did not pass a $postid, try to find the current post id from $post global;
        if($postid == 0 && $postid == ''){
            global $post;
            if(isset($post->ID) && $post->ID != '0')
               $postid = $post->ID;
        }
    
       // return false if no post id or url
        if($postid == 0 || $postid == '' || $url == '' )
            return false;
    
       // make sure active is either 1 or 0 (yes or no)
        $active = (int) $active > 0 ? 1 : 0; 
    
       // make sure redirect type is one of the allowed ones
        $type = $type != '301' && $type != '302' && $type != '307' ? '301' : $type;
    
       // add post meta
        update_post_meta($postid,'_pprredirect_active', $active);
        update_post_meta($postid,'_pprredirect_type', $type);
        update_post_meta($postid,'_pprredirect_url', $url);
    
        //return true so user knows if success
        return true;
    }

    Then to use, you would do it something like this (assuming you want to check it after you add it):

    $add_meta = set_redirect($post->ID, 301, 'http://something.com/new-url/');
    if($add_meta){
     ... do whatever on success
    }else{
     ... do something else for fail
    }

    Or just like this if you do not need a check:
    set_redirect($post->ID, 301, 'http://something.com/new-url/');

    This also assumes that that you already have access to the global $post variable to pass into the function.

    Best of luck,
    Don

Viewing 1 replies (of 1 total)

The topic ‘Set Redirect in Function’ is closed to new replies.