使用自定义分类+帖子标题或帖子标题

时间:2019-05-30 09:46:13

标签: php wordpress wordpress-theming permalinks wordpress-rest-api

我想实现的目标似乎微不足道,但尚未找到解决方案:

我希望能够避免使用自定义postype(即article),并在其永久链接中使用自定义分类法(即site_topic)及其术语(即。 blog),或者如果未设置,请避免使用它,而应使用普通标题。

到目前为止,已尝试过什么来更改永久链接结构: (它确实可以根据需要在仪表板中交换链接,但是访问时的页面会生成404,是的,每次编辑都刷新了永久链接)。

function ms_post_types_permalink_edit( $permalink, $post, $leavename ) {

  if ( in_array( $post->post_type, [ 'article', 'template' ] ) || 'publish' == $post->post_status ) {
    $terms = wp_get_object_terms( $post->ID, 'site_topic' );
    if( $terms ){
        return str_replace( '/' . $post->post_type . '/', '/' . $terms[0]->slug . '/', $permalink );
  }
    return str_replace( '/' . $post->post_type . '/', '/', $permalink );
}
 return str_replace( '/' . $post->post_type . '/', '/', $permalink );
}

add_filter( 'post_type_link', 'ms_post_types_permalink_edit', 10, 3 );

我们要实现的是一个永久链接结构,在两种情况下都适用于这些自定义笔迹,同时保留其余邮递件的常规永久链接结构:

domain.com/custom-taxonomy-term/custom-post-title

domain.com/post-title

作为奖励,自定义postype在其注册中具有以下内容:

....
'rewrite' => [
  'with_front' => false,
  'slug' => false,
]
....

我也尝试结合以上内容进行以下操作或同时进行以下操作:

function ms_post_types_rewrite_rule() {
    add_rewrite_rule('article/([^/]*)/?$', 'index.php?article=$matches[1]', 'top');
    add_rewrite_rule('article/([^/]*)/([^/]*)?$', 'index.php?site_topic=$matches[1]&article="$matches[2]', 'top');
}

add_action('init', 'ms_post_types_rewrite_rule');

function ms_pre_get_posts( $query ) {

  if ( ! $query->is_main_query() ) {
    return;
  }

  if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
    return;
  }
  if ( ! empty( $query->query['name'] ) ) {
    $query->set( 'post_type', [ 'article' ] );
  }
}

add_action( 'pre_get_posts', 'ms_pre_get_posts' );

1 个答案:

答案 0 :(得分:0)

在活动主题function.php文件中使用以下代码

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

        $terms = get_the_terms( $post->ID, 'site_topic' );
        if ( !empty( $terms ) ){
        // get the first term
        $term = array_shift( $terms );

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

        $post_link = str_replace( '/' . $post->post_type . '/', '/' . $terms->slug . '/', $post_link );
    }
        return $post_link;
    }
    add_filter( 'post_type_link', 'remove_ra_slug', 10, 3 );

仅仅去除弹头是不够的。现在,您将获得404页面,因为WordPress只希望帖子和页面具有这种行为。您还需要添加以下内容:

function parse_ra_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( 'article' ) );
    }
}
add_action( 'pre_get_posts', 'parse_ra_request' );

经过测试,效果很好

相关问题