wordpressurl-rewritingnextgen-gallery

clean urls in wordpress using nextgen gallery plugin


Im using the NextGEN Gallery Plugin. Currently i'm getting the category id by mysite.com/photography?cat=weddings

In my page.php, I get the category thats in the url and populate the page based of the category.

$cat = $_GET['cat'];
if($cat == 'portraits'){ $cat = 'where galleryid = 5'; }
if($cat == 'weddings'){ $cat = 'where galleryid = 3'; }
if($cat == 'outdoor'){ $cat = 'where galleryid = 4'; }

$q = $wpdb->get_results("
   select filename, meta_data, galleryid, gal.name, pid
   from wp_ngg_pictures as pic
   join wp_ngg_gallery as gal on (gal.gid = pic.galleryid)
   {$cat}
");

I want to just do this /mysite.com/photography/weddings and have no query string in the URL. I also would rather not do all these if statements to grab the ID. I dont want the ID to be in the URL at all so I want a good readable url.

Does wordpress have an easy way of doing this?


Solution

  • Add this to your functions.php to add a new rewrite rule:

    function my_add_rewrites() {
        global $wp_rewrite;
        $wp_rewrite->add_rule('photography/([^/]+)/?', 'index.php?pagename=photography&photocat=$matches[1]', 'top');
    }
    add_action( 'init', 'my_add_rewrites' );
    
    function my_query_vars( $query_vars ) {
        $query_vars[] = 'photocat';
        return $query_vars;
    }
    add_filter( 'query_vars', 'my_query_vars' );
    

    Then in your page.php, add:

    global $wp, $wpdb;
    // Get the query var
    $photocat = $wp->query_vars['photocat'];
    // Get the gallery ID
    $gid = $wpdb->get_var( "SELECT gid FROM $wpdb->ngg_gallery WHERE slug = '$photocat';" );
    // Check if we have a valid value
    $q = FALSE; // Set a default so you can check later
    if( $gid !== NULL ) {
        // Get the images -> could also use $nggdb->get_gallery($gid);
        $q = $wpdb->get_results("
            select filename, meta_data, galleryid, gal.name, pid
            from wp_ngg_pictures as pic
            join wp_ngg_gallery as gal on (gal.gid = pic.galleryid)
            {$gid}
        ");
    }
    

    You should also be able to get your images from a gallery via $nggdb->get_gallery($gid) which may be easier & cleaner.

    Once you have added all the (rewrite) code, go to Settings -> Permalinks and re-save your permalink settings to add the new rewrite rule to the DB.

    mysite.com/photography/weddings should now set the $photocat variable to weddings and pull your images from that gallery.