Adding meta values to permalink

Was able to get this working. Thought I would write down what we did in the hopes that it will help someone in the future (or someone can give me feedback on how to better improve it!)

  1. Registered Custom Rewrite Rules

    add_action('init', 'pub_rewrite_rules');
    
    function pub_rewrite_rules()
    {
        global $wp_rewrite;
    
        $wp_rewrite->add_rewrite_tag( '%pubyear%', '([0-9]{4})', 'pubyear=");
        $wp_rewrite->add_rewrite_tag( "%pubmonth%', '([0-9]{2})', 'pubmonth=");
    }
    
  2. Created Permalink Structure

     function pub_permalink($permalink, $post, $leavename)
     {
         if ( false !== strpos( $permalink, "%publication-type%/%pubyear%/%pubmonth%' ) ) {
    
             $publicationtype = get_the_terms($post->ID, 'publication-type');
             $pubyear = date('Y', get_post_meta($post->ID, 'publication_date', true));
             $pubmonth = date('m', get_post_meta($post->ID, 'publication_date', true));
    
             $rewritecode = array(
                   '%publication-type%',
                   '%pubyear%',
                   '%pubmonth%',
                   $leavename? '' : '%postname%',
             );
    
             $rewritereplace = array(
                   array_pop($publicationtype)->slug,
                   $pubyear,
                   $pubmonth,
                   $post->post_name
             );
    
             $permalink = str_replace($rewritecode, $rewritereplace, $permalink);    
        }
        return $permalink;
    }
    
  3. Registered Taxonomy

  4. Registered Custom Post Type
    wrote rewrite array to include:

     'slug' => 'publications/%publication-type%/%pubyear%/%pubmonth%',
    
  5. flush rewrite rules by going to Permalink Settings page and saving or flush_rewrite_rule()

Leave a Comment