WordPress.org

Support

Support » Plugins and Hacks » Hacks » [Resolved] Dynamically create clean URLs

[Resolved] Dynamically create clean URLs

  • Hey there,

    I’ve written my own page which generates its content via a $_GET variable.
    If I e.g. access mysite.com/partner/?id=2 it will generate the site with all the content associated with id=2 (which is an partner-id).

    Let’s assume id 2 is Cool Company LLC.

    What I want to achieve is that I can also use mysite.com/partner/cool-company-llc/.

    Is there any way to do this? I mean dynamically, linked maybe to a database entry with the slug according to the id. Of course I could also just create a .htaccess-entry for each and every partner. But ehrm – no.

    Thanks for reading! 🙂

Viewing 5 replies - 1 through 5 (of 5 total)
  • I think it will be better to create a custom post type for partners, called “partner”.

    Sure, the whole thing would probably much more cleaner with a custom post type. But in that case I would need to create a whole plugin out of that small script. 😐
    Currently I have my profiles in an independent database which I simply query via wpdb.

    I think I’ll simply go with the .htaccess-solution until my client approves the budget for converting it into a plugin.

    Adan0s, did you ever figure out a way to do this?

    Hey mavrick,

    yes, even though it’s a combination of a modificated page-template, an addition to the functions.php and a custom table in the wordpress-database

    functions.php (put at the end)

    add_filter('query_vars', 'partner_queryvars' );
    
    function partner_queryvars( $qvars )
    {
      $qvars[] = 'slug';
      return $qvars;
    }
    
    add_action('generate_rewrite_rules', 'partner_add_rewrite_rules');
    
    function partner_add_rewrite_rules( $wp_rewrite )
    {
      $new_rules = array(
         'partner/([^/]*)$' => 'index.php?pagename=partner&slug=' .$wp_rewrite->preg_index(1) );
    
      //Add the new rewrite rule into the top of the global rules array
      $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    }

    page-partner.php (put at top)

    $slug = get_query_var('slug');
    if($slug != "") {
    	$partner = $wpdb->get_row($wpdb->prepare("SELECT * FROM partner WHERE slug=%s LIMIT 1",$slug));
    }
    else {
    // no slug, do something generic
    }

    the custom table (in my case called partner) has multiple rows, one of them called slug includes the desired part of the url.

    code should be pretty self-explanatory, just replace partner with your page and slug with your desired variable. if not, don’t hesitate to ask.

    Adan0s, thank you for the quick response. I will be trying this out this week.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘[Resolved] Dynamically create clean URLs’ is closed to new replies.
Skip to toolbar