How to change the post permalink from title plus custom field value

19 views Asked by At

I'm creating streaming website, I have custom post type (watch) and custom field inside the post page(eps_num). When I create new post (title = Super Natural) the post permalink looks like this www.website.com/watch/Super-Natural/ , the (eps_num = 01)

if I have to create new post with same title, ( permalink = /watch/Super-Natural-1/ ) , the (eps_num = 05).

I want to change a post permalink to (/watch/Super-Natural-05/ ), it means to take the title + custom filed (eps_num) value in the permalink.

this is what I had tried

add_filter( 'post_type_link', 'wpse_64285_external_permalink', 10, 2 );
function wpse_64285_external_permalink( $link, $post )
{
    $meta = get_post_meta( $post->ID, 'eps_eps-num', TRUE );
    $url  = esc_url( filter_var( $meta, FILTER_VALIDATE_URL ) );

    return $url ? $url : $link;
}

and this

add_filter( 'pt_cv_ctf_value', 'cpt_link_to_cfv', 100, 3 );
function cpt_link_to_cfv( $args, $key, $post ) {
    if ( $key == 'eps_eps-num' ) {
        $args = sprintf( '<a href="%s">%s</a>', get_permalink( $post ), $args );
    }

    return $args;
}

how I can do it ??

1

There are 1 answers

0
Mohamed Omar On

I have found the answer

function custom_post_permalink($permalink, $post) {
    if (get_post_type($post) == 'watch') {
        $custom_field_value = get_post_meta($post->ID, 'eps_eps-num', true);
        $post_title = get_the_title($post->ID);

        // Manipulate the permalink structure as needed, for example:
        $new_permalink = $post_title . '-' . $custom_field_value; // This is just a basic example
        
        return home_url(user_trailingslashit($new_permalink));
    }
    return $permalink;
}
add_filter('post_type_link', 'custom_post_permalink', 10, 2); 

this is the important line to update the permalink

return home_url(user_trailingslashit($new_permalink));

and any one need to use it, you should flash /options-permalink from admin panel