最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What are the best practices for including a custom post's taxonomy in the URL using ACF Pro custom posts and taxonomies?

programmeradmin0浏览0评论
Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 4 days ago.

Improve this question

I have a custom post type and a custom taxonomy created with ACF Pro. The post type:

And the taxonomy:

Then in functions.php, I have this code:

add_action(
    'init',
    function() {
        add_rewrite_rule(
            '^(?:tour-category-1|tour-category-2|tour-category-3)/([^/]+)/?$',
            'index.php?post_type=tour&name=$matches[1]',
            'top',
        );
    },
);
add_filter(
    'post_type_link',
    function(string $post_link, WP_Post $post) {
        static $placeholders_to_taxonomies = [
            '%tourcategory%' => 'tour-category',
        ];

        foreach ($placeholders_to_taxonomies as $placeholder => $taxonomy) {
            if (str_contains($post_link, $placeholder)) {
                $term    = get_primary_term($taxonomy, $post->ID);
                $replace = 'uncategorized';

                if ($term instanceof WP_Term) {
                    $replace = $term->slug;
                }

                $post_link = str_replace($placeholder, $replace, $post_link);
            }
        }

        return $post_link;
    },
    10,
    2,
);

function get_primary_term(string $taxonomy, int $post_id): WP_Term|false
{
    $primary_term = false;
    $terms = get_the_terms($post_id, $taxonomy);
    $terms = is_wp_error($terms) ? [] : $terms;
    $terms = $terms ?: [];

    if ($terms) {
        [$primary_term] = $terms;
    }
}

(For the call to add_rewrite_rule, the category slugs in the regex are not the actual categories that are being used on the site.)

This works, but every time the client adds a category I have to add the new category slug to the regex. I could change it to retrieve all the categories and add a rewrite rule for each one, but I don't know if this would slow down the site or if there is a better approach than that.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论