Search code examples
wordpresspostpermalinks

How I customize permalink with year selected from custom taxnomy in post then post tile in wordpress


I want to add "year" of custom taxonomy of post selected in custom permalinks with post title E.g. suppose in my post have custom taxonomy with year . so I can select year for specific post . I have select year 2018 then my permalink should be http ://mysite/2018/post-title I have select year 2019 then my permalink should be http ://mysite/2019/post-title

means permalink should be depend on select year in post.

I checked on google and do R&D but nothing found related this . If any one have idea about this then please help me


Solution

  • I got the answer

    Add below code in functions.php file

    add_filter('post_link', 'postcustom_permalink', 10, 3);
    add_filter('post_type_link', 'postcustom_permalink', 10, 3);
     
    function postcustom_permalink($permalink, $post_id, $leavename) {
        if (strpos($permalink, '%winneryear%') === FALSE) return $permalink;
         
            // Get post
            $post = get_post($post_id);
            if (!$post) return $permalink;
     
            // Get taxonomy terms
            $terms = wp_get_object_terms($post->ID, 'winneryear');   
            if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
            else $taxonomy_slug = 'no-year';
     
        return str_replace('%winneryear%', $taxonomy_slug, $permalink);
    } 
    

    and then after add %winneryear% in the custom permalink in backend.