簡體   English   中英

自定義永久鏈接,在Wordpress自定義帖子類型上使用動態重寫標記

[英]Custom permalink with dynamic rewrite tags on a Wordpress custom post type

我有一個名為location的自定義帖子類型,我正在嘗試將此類型的帖子設置為現有頁面的子項,以實現這樣的永久鏈接結構:

example.com/alabama  <-- Page with generic content
example.com/alabama/locations  <-- Another page, child of a state page
example.com/alabama/locations/location-name  <- Custom type, child of alabama/locations seen above and titled `Location Name`

最接近我必須在兩個不同的帖子類型之間創建層次關系是通過一個元框,我可以在保存它們時將帖子ID post_parent為我的自定義類型帖子的post_parent 盡管頁面ID確實保存在CPT post_parent字段中,但它對永久鏈接沒有影響。 它們按rewrite CPT選項中的定義進行。 但我不知道如何使['rewrite']['slug']選項動態化,或者甚至可能。

這就是我的帖子類型的定義方式:

add_action( 'init', function() {
  register_post_type( 'location', [
    'label' => 'Location',
    'menu_icon' => 'dashicons-location-alt',
    'supports' => [ 'title', 'editor', 'custom-fields' ],
    'public' => true,
    'hierarchical' => false,
    'has_archive' => false,
    'rewrite' => false,
  ] );
} );

如何配置位置的重寫規則以獲得我需要的永久鏈接?

我假設所有的location帖子都有一個永久鏈接結構,如下所示:

example.com/{STATE NAME}/locations/{CPT SLUG}

示例URL地址:

http://example.com/alabama/locations/location-1
http://example.com/alabama/locations/location-2
http://example.com/new-york/locations/location-3

所以,如果這是正確的,那么:

•使用add_rewrite_rule()函數為這些永久鏈接添加自定義重寫規則。

•您不需要/locations/ Page。

add_action( 'init', function(){
    // Handles requests to `your-site-domain.com/{STATE NAME}/locations/{CPT SLUG}`
    add_rewrite_rule(
        '([^/]+)/locations/([^/]+)(?:/([0-9]+))?/?$',
        'index.php?location=$matches[2]&page=$matches[3]&state_name=$matches[1]',
        'top'
    );

    // Allows you to retrieve the `state_name`; for example using `get_query_var()`.
    add_rewrite_tag( '%state_name%', '([\w\-]+)' );
} );

(您可以將state_name更改為其他名稱;這取決於您。並且不要忘記刷新重寫規則 - 轉到“永久鏈接設置”頁面並單擊“保存更改”按鈕,而不必進行任何更改。)


接下來,當您創建或編輯location信息時,請將post_parent自定義字段的值設置為“狀態頁面”的ID - 例如/alabama/ Page。

此代碼將過濾get_permalink()輸出,並返回location帖子的相應永久鏈接:

add_filter( 'post_type_link', 'so51217355_post_type_link', 10, 2 );
function so51217355_post_type_link( $permalink, $post ) {
    if ( 'location' === $post->post_type ) {
        $page_id = get_post_meta( $post->ID, 'post_parent', true );

        $state_name = ( is_numeric( $page_id ) && $page_id ) ?
            get_post_field( 'post_name', $page_id ) : null;

        // Make sure the post is associated to a valid 'state Page'.
        if ( $state_name ) {
            $permalink = $state_name . '/locations/' . $post->post_name;
            $permalink = home_url( user_trailingslashit( $permalink ) );
        }
    }

    return $permalink;
}

例如, get_permalink( 123 )將返回http://example.com/alabama/locations/location-1 ,如果location帖子的slug是location-1 ,並且其'state Page'是/alabama/


UPDATE

當請求永久鏈接時(即用戶訪問example.com/{STATE NAME}/locations/{CPT SLUG} ),您要確保“狀態頁面”和location帖子都存在, 確保“狀態頁面”確實與location貼相關聯,那么此代碼可以幫助您:

// Validates the `state_name` of the current page/URL.
add_action( 'parse_request', 'so51217355_parse_request' );
function so51217355_parse_request( $wp ) {
    if ( ! empty( $wp->query_vars['state_name'] ) &&
        ! empty( $wp->query_vars['location'] ) ) {
        global $wpdb;

        $page_id = $wpdb->get_var( $wpdb->prepare(
            "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s",
            $wp->query_vars['state_name']
        ) );

        if ( ! is_numeric( $page_id ) || ! $page_id ) {
            $wp->query_vars['error'] = '404';

            // Don't let WordPress finds a post with nearest match.
            remove_action( 'template_redirect', 'redirect_canonical' );

            return;
        }

        $post_id = $wpdb->get_var( $wpdb->prepare(
            "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s",
            $wp->query_vars['location']
        ) );

        $page_id2 = get_post_meta( $post_id, 'post_parent', true );
        if ( (int) $page_id2 !== (int) $page_id ) {
            $wp->query_vars['error'] = '404';

            // Don't let WordPress finds a post with nearest match.
            remove_action( 'template_redirect', 'redirect_canonical' );
        }
    }
}

更新#2

請參閱此圖像下方代碼中的// Comment - 請參閱_so51217355_admin_ajax_js()函數。

在此輸入圖像描述

add_action( 'wp_ajax_so51217355_admin_ajax', '_so51217355_admin_ajax_php' );
function _so51217355_admin_ajax_php() {
    $post_id = filter_input( INPUT_POST, 'post_id' );
    echo get_sample_permalink_html( $post_id );
    wp_die();
}

add_action( 'admin_print_footer_scripts', '_so51217355_admin_ajax_js', 11 );
function _so51217355_admin_ajax_js() {
    $screen = get_current_screen();
    if ( 'location' === $screen->id ) :
    ?>
<script>
// This script will sync the Permalink under the big/main post title box on
// the Edit Post page; but only if and when editing or deleting the custom
// field as in `meta_key` below. Make sure to change it, if necessary.
jQuery( function( $ ){
    var meta_key = 'post_parent';

    function ajax() {
        $.post( ajaxurl, {
            action: 'so51217355_admin_ajax',
            post_id: $( '#post_ID' ).val()
        }, function( s ){
            $( '#edit-slug-box' ).html( s );
        } );
    }

    function _go( e, a ) {
        var $input = $( a.target ),
            mid, mkey;

        if ( /^meta\-(\d+)\-submit$/.test( $input.attr( 'name' ) ) ||
            /^deletemeta\[(\d+)\]$/.test( $input.attr( 'name' ) ) ) {
            mid = RegExp.$1;
            mkey = $( 'input[name="meta[' + mid + '][key]"]' ).val();

            if ( meta_key === mkey ) {
                ajax();
            }
        }
    }

    $( '#the-list' )
        .on( 'wpListAddEnd', _go )
        .on( 'wpListDelEnd', _go );
} );
</script>
    <?php
    endif;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM