1

I would like WordPress to handle an incoming url with a variable parameter and not throw a 404. Basically, an incoming url could look like this:

http://mysite.com/custom-post-type/some-post/?promo=12er34 

I then pass that last segment into a signup form for promotions. Obviously, hitting this url directly would throw a 404.

Is there anyway to setup a conditional in my custom post type that would allow a match if the incoming url has an additional specified segment?

1 Answer 1

1

In your custom post-type template, you could do this:

$code = isset( $_GET[ 'promo' ] ) ? sanitize_text_field( $_GET[ 'promo' ] ) : '';

By the way, the parameter in your url should have a ? before promo.

Like this: http://mysite.com/custom-post-type/some-post/?promo=12er34

Update:

If you want to get this value regardless of whether you're on a custom post-type or the default post-type, try this in your functions.php:

function get_promo_code( $wp ) {
    if( ! is_single() )
        return;

    // Do whatever you want with the promo code here.
    $code = isset( $_GET[ 'promo' ] ) ? sanitize_text_field( $_GET[ 'promo' ] ) : '';
}

add_action( 'wp', 'get_promo_code' );
6
  • The more I think about this the more I think it would make sense to make this global. In other words, I don't want to limit this to custom post types. I'd like to match/allow incoming urls with /?promo=12er34 no matter what the post or page url is. Maybe this is a .htaccess thing?
    – intheusa
    Feb 26, 2013 at 21:48
  • I've updated my answer to illustrate how to catch the promo code for default post-types, as well as custom post-types. Feb 26, 2013 at 22:34
  • Thanks Spencer, you know what though...I'm an idiot for not even trying this but without the above function, if I slap a string onto the end of my wp url like custom-post-type/?promo=125234 it works fine :/ I guess if it's a query parameter it doesn't throw a 404...? Weird, I just assumed wp would throw a 404 without even trying it. Am I missing something here?
    – intheusa
    Feb 26, 2013 at 23:16
  • It won't throw a 404 if the uri is valid. Appending a query variable like ?promo=123 has no affect on the uri itself, in this case. :) Also, the function I gave you only gets the query variable it doesn't allow it to not throw a 404. Feb 26, 2013 at 23:23
  • Right. It's all so clear now...crap. Sorry to waste your time.
    – intheusa
    Feb 26, 2013 at 23:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.