Wordpress 中相同 post 的多个 uri

Multiple uri to same post in Wordpress

我想在 Wordpress 中使两个 uri 指向相同的 post 但没有重定向, mysite.co.uk/awesome-post mysite.co.uk/?p=12

我希望这两个 uri 指向同一个 post 但是当你到达页面时 uri 不应该改变。

我知道的唯一解决方案是复制你的 post 并从中获得第二个 link 并隐藏循环中的副本,如果你希望后端。

为此,您必须使用 save_post 操作和 plugin/theme 激活挂钩来复制已发布的 posts(这可以是初始化挂钩,但您需要小心这只有一次).

首先你必须遍历所有 post 并复制

add_action('switch_theme', 'your_prefix_setup_options');

function your_prefix_setup_options () {
  // WP_Query arguments
    $args = array (
        'post_type'              => array( 'post' )
    );

    // The Query
    $query = new WP_Query( $args );

    // The Loop
    if ( $query->have_posts() ) {

        while ( $query->have_posts() ) {
            $query->the_post();

            // duplicate post like this
            your_prefix_post_duplicate( get_the_ID(), get_the_title(), get_the_content(), get_post_thumbnail_id() );

        }

    } else {
        // no posts found
    }

    // Restore original Post Data
    wp_reset_postdata();
}

function your_prefix_post_duplicate($post_id, $title, $content, $attachment){


    $post_id = $post_id;
    $post_name = $title;
    $content = $content;
    $attachment = $attachment;


    $slug = str_replace( " ", "-", $post_name );
    $slug = strtolower($slug);

    $post_data = array(
        'post_content' => $content,
        'comment_status'    =>  'closed',
        'ping_status'       =>  'closed',
        'post_author'       =>  0,
        'post_name'     =>  $slug,
        'post_title'        =>  $post_name,
        'post_status'       =>  'published',
        'post_type'     =>  'post'
    );

    $prefix = 'your_prefix__';
    //create your duplicate post
    $duplicate_post_id = wp_insert_post( $post_data );
    set_post_thumbnail( $duplicate_post_id, $attachment );
    add_post_meta( $duplicate_post_id, $prefix . 'duplicate', TRUE );
    //get duplicate link
    $perma_link = get_permalink ( $duplicate_post_id );


    //set this link to your post as meta
    add_post_meta( $post_id, $prefix . 'duplicate_url', $perma_link );

}

// now you can get second uri for fb like/share
$second_link = get_post_meta(get_post_ID(),$prefix . 'duplicate_url', true);

//and you can use the meta and ignore duplicate post from showing on loop 
// or in advance you can use pre get post to hidethese duplicates from front end & back end permanently
get_post_meta(get_post_ID(),$prefix . 'duplicate', true);