WordPress Rewrite API

Read more on custom rewrite rules and the rewrite API: https://codex.wordpress.org/Rewrite_API/add_rewrite_rule

I needed to render a page with various url parameters to set the og/meta tags properly. So for example: http://url.com/share/?content_id=188&share_id=abc1234&img_count=3. Facebook will ignore everything after ‘share/’, effectively breaking my shit. So using the following, I can make a prettier url to render that content and facebook/twitter should scrape it just fine:

// needed a function to get a page ID based on the page slug (in this case 'share') because the ID will not be consistent across environments
function get_id_by_slug($page_slug) {
     $page = get_page_by_path($page_slug);
     if ($page) {
          return $page->ID;
     } else {
          return null;
     }
}

function custom_rewrite_tag() {
     add_rewrite_tag('%content_id%', '([^&]+)');
     add_rewrite_tag('%share_id%', '([^&]+)');
     add_rewrite_tag('%img_count%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);

function share_rewrite() {
     $share_page_id = get_id_by_slug('share');
     add_rewrite_rule('^share/([^/]*)/([^/]*)/([^/]*)/?','index.php?page_id='.$share_page_id.'&content_id=$matches[1]&share_id=$matches[2]&img_count=$matches[3]','top');
     add_rewrite_rule('^share/([^/]*)/([^/]*)/?','index.php?page_id='.$share_page_id.'&content_id=$matches[1]&share_id=$matches[2]','top');
}
add_action('init', 'share_rewrite', 10, 0);