I created a plugin that is basically a crud to write to the mysql database. I want to know how to display the data on a wordpress page. I'm reading about url rewrites but it seems rewrites are for regular post and just changing the url. I can't seem to find any tutorials on this.

so when I go example.com/gallery/1/5 it will take me to the gallery with id: 1 and show me the 5th image.


I got a little piece of code here, but it should/could probably be improved.

  • Create new query_vars
  • Create new rewrite rule
  • Redirect to specific template which then handles your parameters

Create new query vars

function register_gallery_query_vars($vars) {
   $vars[] = 'gallery_id';
   $vars[] = 'image_id';
   return $vars;
add_filter('query_vars', 'register_gallery_query_vars');

Add rewrite rule

function custom_rewrite_gallery() {
  add_rewrite_rule('^gallery/([0-9]+)/([0-9]+)/?', 'index.php?gallery=$matches[1]&image=$matches[2]', 'top');
// Change this to run ONLY on plugin activation
// Also have in mind that you need to flush rewrite rules if you change them
add_action('init', 'custom_rewrite_events');

Redirect to template

function gallery_template_redirection($template)
    global $wp_query;
    if(isset($wp_query->query_vars['gallery'])) { return dirname(__FILE__).'/gallery.php'; }
     else return $template;
add_filter('template_include', 'gallery_template_redirection', 1, 1);

Your gallery.php can then use get_query_var() to read the values and work on with them.

| improve this answer | |
  • Well, if you got something very specific, like showing a gallery, it might come in handy to have another file handle that page. gallery.php should include the code that builds your gallery, so you need to redirect it. That happens with that last function/hook. – flomei Nov 17 '15 at 23:01
  • It has to be placed in your theme folder. – flomei Nov 17 '15 at 23:39
  • Because you will need to work with the query vars in your gallery.php. But you have to define them in the functions.php and add them to your WP standard query vars. – flomei Nov 17 '15 at 23:47
  • You seriously need to start from the beginning with your plugin. Focus on one task and finish it (saw your other questions). Research for yourself and try to understand what happens. You do not seem to have understand anything of what I´ve written, that will cause serious problems when you work on... – flomei Nov 17 '15 at 23:52
  • No, I won´t use the chat. This code works, in variations, fine on several sites I´m maintaining. You need to understand what you do, not just copy code. Sorry. – flomei Nov 17 '15 at 23:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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