从固定链接中删除所有POST类型的POST类型插件

时间:2019-07-23 作者:Gidromasservis QSC

我知道以前也有人问过类似的问题,但这是一个新帐户,我不能在那里发表评论。此代码从permalink中删除post类型slug。但我有很多帖子类型。如何将此代码用于我的所有帖子类型

 function na_remove_slug( $post_link, $post, $leavename ) {

    if ( \'my_custom_post_type\' != $post->post_type || \'publish\' != $post->post_status ) {
        return $post_link;
    }

    $post_link = str_replace( \'/\' . $post->post_type . \'/\', \'/\', $post_link );

    return $post_link;
}
add_filter( \'post_type_link\', \'na_remove_slug\', 10, 3 );
function na_parse_request( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query[\'page\'] ) ) {
        return;
    }

    if ( ! empty( $query->query[\'name\'] ) ) {
        $query->set( \'post_type\', array( \'my_custom_post_type\') );
    }
}

1 个回复
最合适的回答,由SO网友:Dharmishtha Patel 整理而成

 function gp_remove_cpt_slug( $post_link, $post ) {
        if ( \'race\' === $post->post_type && \'publish\' === $post->post_status ) {
            $post_link = str_replace( \'/\' . $post->post_type . \'/\', \'/\', $post_link );
        }
        return $post_link;
    }
    add_filter( \'post_type_link\', \'gp_remove_cpt_slug\', 10, 2 );
此时,尝试查看链接将导致404(找不到页面)错误。这是因为WordPress只知道帖子和页面可以有类似于域的URL。com/post名称/或域。com/页面名称/。我们需要告诉它,我们的自定义帖子类型的帖子也可以有类似域的URL。com/cpt post name/。

<?php
/**
 * Have WordPress match postname to any of our public post types (post, page, race).
 * All of our public post types can have /post-name/ as the slug, so they need to be unique across all posts.
 * By default, WordPress only accounts for posts and pages where the slug is /post-name/.
 *
 * @param $query The current query.
 */
function gp_add_cpt_post_names_to_main_query( $query ) {
    // Bail if this is not the main query.
    if ( ! $query->is_main_query() ) {
        return;
    }
    // Bail if this query doesn\'t match our very specific rewrite rule.
    if ( ! isset( $query->query[\'page\'] ) || 2 !== count( $query->query ) ) {
        return;
    }
    // Bail if we\'re not querying based on the post name.
    if ( empty( $query->query[\'name\'] ) ) {
        return;
    }
    // Add CPT to the list of post types WP will include when it queries based on the post name.
    $query->set( \'post_type\', array( \'post\', \'page\', \'race\' ) );
}
add_action( \'pre_get_posts\', \'gp_add_cpt_post_names_to_main_query\' );
就是这样!只需将这些代码示例中的两个race实例都更改为自定义post类型的slug,并用您想要的任何函数前缀替换gp\\u1(您的首字母缩写就可以了),您应该已经全部设置好了。可能还需要转到“设置”>“永久链接”,并将永久链接结构保存到/%postname%/中。

相关推荐

WP JSON list all permalinks

Scenario我正在考虑编写一个自定义的wp json端点,以列出我的wordpress中每个帖子的所有永久链接。Question是否可以使用rest查询+筛选器来完成此操作?例如:。http://wpsite.com/wp-json/wp/v2/posts?filter[only-permalinks]当前的解决方案最后我编写了一个自定义端点,代码如下:添加到函数的底部。phpfunction get_all_slugs() { $posts = get_posts( array(&#