Auto add custom taxonomy to permalink when save

admin2025-06-05  1

I've search this site and I can't find a way to automatically add custom taxonomy to a post permalink For example, I have a post with the title "mysamplepost" and taxonomy "years" with value "2018". So when I hit publish the post permalink becomes ""

I saw this post here but it doesn't function like I want to. Instead it inserts custom taxonomy before post title .

Thank you for whoever provides an answer

I've search this site and I can't find a way to automatically add custom taxonomy to a post permalink For example, I have a post with the title "mysamplepost" and taxonomy "years" with value "2018". So when I hit publish the post permalink becomes "https://example/mysamplepost-2018"

I saw this post here but it doesn't function like I want to. Instead it inserts custom taxonomy before post title .

Thank you for whoever provides an answer

Share Improve this question edited Dec 2, 2018 at 1:45 butlerblog 5,1413 gold badges28 silver badges44 bronze badges asked Feb 14, 2018 at 5:54 juicebyahjuicebyah 1114 bronze badges 2
  • Do you want to append 2018 on the fly or want to append and store in database? – obiPlabon Commented Feb 14, 2018 at 7:04
  • append on database also so make it permanent man – juicebyah Commented Feb 14, 2018 at 10:55
Add a comment  | 

1 Answer 1

Reset to default 0

Please check the following code, you have to assign the custom taxonomy name to $taxonomy variable. And only the first taxonomy term will be appended to the post slug.

add_filter( 'wp_insert_post_data', function( $data, $postarr ) {
    /**
     * Only for post posttype and when the post is created
     */
    if ( empty( $postarr['save'] ) && isset( $data['post_type'] ) && 'post' === $data['post_type'] ) {
        $taxonomy  = 'custom-taxonomy-name'; // Add your custom taxonomy name
        $tax_terms = array();
        $slug      = '';

        /**
         * Make sure custom taxonomy is really assigned
         */
        if ( isset( $postarr['tax_input'] ) && isset( $postarr['tax_input'][ $taxonomy ] ) ) {
            $tax_terms = array_filter( $postarr['tax_input'][ $taxonomy ] );
        }

        /**
         * Only the first term slug will be appended
         */
        if ( count( $tax_terms ) ) {
            $term = get_term( current( $tax_terms ), $taxonomy );
            if ( ! is_wp_error( $term ) && ! is_null( $term ) ) {
                $slug = '-' . $term->slug;
            }
        }

        /**
         * Append the slug
         */
        if ( $slug ) {
            $data['post_name'] .= $slug;
        }
    }
    return $data;
}, 10, 2 );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749135338a316659.html

最新回复(0)