首页 > 解决方案 > Wordpress 如何将帖子类型用作带有永久链接的页面?

问题描述

问题是如何在 WordPress 中创建一个类似于 node express 的路由。
/gallery/{:id or :name} 进入画廊页面

我目前有项目,画廊页面(他们都使用模板)

 /**
 * Template Name: Gallery page
 *
 * @package WordPress
 * @subpackage  A Theme
 * @since  A Theme 1.0
 */

创建了一个包含图像和附加到项目的自定义画廊类型。

将主题名称替换为 A

add_action( 'init', 'gallery_post_type' );
function gallery_post_type() {
    register_post_type( 'gallery',
        array(
        'labels' => array(
            'name'               => __('Gallery Page - gallery', 'A'),
            'singular_name'      => __('Gallery', 'A'),
            'add_new_item'       => __('Add Gallery', 'A'),
            'edit_item'          => __('Edit Gallery', 'A'),
            'new_item'           => __('New Gallery', 'A'),
            'view_item'          => __('View Gallery', 'A'),
            'search_items'       => __('Search Gallery', 'A'),
            'not_found'          => __('No Gallery Found', 'A'),
            'not_found_in_trash' => __('No Gallery found in Trash', 'A')
        ),
        'description'          => 'Gallery in the gallery page',
        'hierarchical'         => false,
        'menu_icon'            => 'dashicons-networking',
        'menu_position'        => 5,
        'public'               => true,
        'show_in_admin_bar'    => false,
        'show_in_nav_menus'    => true,
        'show_ui'              => true,
        'supports'             => array('title')
        ));
}

当用户单击项目块中的链接时,我想将路径更改为画廊页面。

类似于 domain/gallery/project-name/ 但它一直显示未找到或什么也没有。查看图库页面的唯一方法是访问域/图库

我应该怎么做才能创建画廊/项目名称?图库页面 - 固定链接:http://wordpresslocal-clone.local/gallery/ {:name} <- 我可以像 node express 一样做这样的事情吗

图库帖子 - 固定链接:http://wordpresslocal-clone.local/gallery/test/

我按照评论建议尝试了这段代码

add_action( 'init', 'wpse26388_rewrites_init' );
  function wpse26388_rewrites_init(){
      add_rewrite_rule(
          'gallery/([a-zA-Z_0-9]+)/?$',
          'index.php?pagename=gallery&project_name=$matches[1]',
          'top' );
  }
  add_filter( 'query_vars', 'wpse26388_query_vars' );
  function wpse26388_query_vars( $query_vars ){
      var_dump($query_vars);
      $query_vars[] = 'project_name';
      return $query_vars;
  }

标签: wordpress

解决方案


请检查一下,这在我的最后工作正常:

add_action('init', 'mjt_gallery_post_init');
function mjt_gallery_post_init() {
    global $data;
    register_post_type(     
        'gallery',      
    array(          
        'labels' => array(              
        'name' => 'Gallery Page',   
        'singular_name' => 'Gallery'    
        ),  
        'public' => true,
        'has_archive' => 'gallery', 
        'rewrite' => array('slug' => 'gallery', 
        'with_front' => true),
        'supports' => array('title', 'editor', 'author',  'revisions', 'custom-fields' ),   
        'can_export' => true,
        )
    );
}

并且请重新保存永久链接设置。


推荐阅读