Skip to content

Instantly share code, notes, and snippets.

@ericmann
Created September 26, 2012 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericmann/3788867 to your computer and use it in GitHub Desktop.
Save ericmann/3788867 to your computer and use it in GitHub Desktop.
Auto-generate URLs

#The Problem

I need to create custom links based on the current page URL within WordPress. The system needs to work with both pretty and default permalinks. I have a custom rewrite endpoint defined that needs to be added.

So if the URL of the page is http://site.url/?p=25 I need to create http://site.url/?p=25&custom=1

If the URL is http://site.url/2012/post-slug I need to create http://site.url/2012/post-slug/custom

I can't find a built-in function to do this, so I'm thinking I'll need to build my own to do this. Some pseudo-code:

function create_link() {
    $current = get_current_page_url(); // Not a real fn, just get the current url

    $structure = get_option( 'permalink_structure' );

    if ( ! empty( $structure ) ) {
        $new = add_query_arg( 'custom', 1, $current );
    } else {
        $new = trailingslashit( $current ) . 'custom';
    }

    return $new;
}

Does this logic make sense? Is there an easier/better way to do it? What's the best way to get the current page URL?

#The Solution

OK, after some feedback on Twitter, here's the function I ended up with:

public function get_custom_link() {
    $permalink = get_permalink();

    $structure = get_option( 'permalink_structure' );

    if ( empty( $structure ) ) {
        $new = add_query_arg( 'custom', 1, $permalink );
    } else {
        $new = trailingslashit( $permalink ) . 'custom/1';
    }

    return $new;
}
@trepmal
Copy link

trepmal commented Sep 26, 2012

Is there a reason get_permalink() wouldn't work?

@johnpbloch
Copy link

What you're doing here is pretty much the best way to do it.

As far as getting the current url, leaving the $current arg out of add_query_arg() will make it default to the current requested url (the function uses $_SERVER['REQUEST_URI'] to get the uri and rebuilds the url from there). For fancy permalinks, is it possible to use a relative url? I mean, since it's the current page, it would work...

If not, I'd recommend checking out how add_query_arg() builds the url.

@johnpbloch
Copy link

Of course, if you need to get the current url without reinventing the wheel, you could just do this:

remove_query_arg( 'temp', add_query_arg( 'temp', 1 ) );

@danielbachhuber
Copy link

Sadly, the best way to get the current URI is $_SERVER['REQUEST_URI']

It sounds like you want to add a rewrite endpoint: http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment