Issue with custom rewrite rules for custom post types.
-
I registered a post type named ‘work,’ and I need to modify the permalink structure for this post type to an string consisting of 18 characters. I use the following code to rewrite the rules, but when I open a ‘work’ post page, it goes to the ‘work’ archive page instead. I don’t know where the issue is.
register post type:
<?php namespace BLANPI\App; defined('ABSPATH') || exit; use BLANPI\App\Traits\Singleton; class Blanpi_Post_Type { use Singleton; protected function __construct() { $this->setup_hooks(); } protected function setup_hooks() { add_action('init', [$this, 'blanpi_create_post_type']); } public static function blanpi_create_post_type() { $work_args = array( 'labels' => array( 'name' => __('Work', 'blanpi'), 'singular_name' => __('Work', 'blanpi'), 'menu_name' => __('Work', 'blanpi'), 'admin menu', 'name_admin_bar' => __('Work', 'blanpi'), ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => true, 'menu_position' => null, 'show_in_rest' => true, 'supports' => array('title', 'editor', 'post-formats', 'author', 'custom-fields'), 'menu_icon' => 'dashicons-format-gallery' ); register_post_type('work', $work_args); } }
rewrite:
<?php namespace BLANPI\App; defined('ABSPATH') || exit; use BLANPI\App\Traits\Singleton; class Blanpi_Setup { use Singleton; protected function __construct() { $this->setup_hooks(); } protected function setup_hooks() { add_filter('post_link', [$this, 'custom_permalink'], 10, 3); add_filter('post_type_link', [$this, 'custom_permalink'], 10, 3); add_action('init', [$this, 'custom_rewrite_rules']); } public function custom_rewrite_rules() { add_rewrite_rule( '^work/([^/]+)/?$', 'index.php?post_type=work&p=$matches[1]', 'top' ); add_rewrite_rule( '^work/([^/]+)/([^/]+)/?$', 'index.php?post_type=work&name=$matches[2]', 'top' ); } public function custom_permalink($permalink, $post, $leavename) { if ($post && $post->post_type == 'work') { $permalink = home_url('/') . substr(md5($post->ID), 0, 18) . '/'; } return $permalink; } }
I want change the url link this:
https://webiste.com/8212a829abo92822kl
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
- The topic ‘Issue with custom rewrite rules for custom post types.’ is closed to new replies.