Use a variable in Custom Post Type permalink
-
Hey,
i have a permalink issue but i don’t know to solve it.
I want to use a variable in my custom post type permalinks like:
https://www.domain.com/variable/postname
This is all i want and i don’t can’t solve it.I have try it with this code but always i become a 404 Error.
function post_type_profiles() { register_post_type ( 'custompost', array ( 'label' => __('custompost'), 'public' => true, 'show_ui' => true, 'has_archive' => true, 'hierarchical' => true, 'rewrite' => array( 'with_front' => false, 'slug' => '%city%' ), 'supports' => array ( 'title', 'editor', 'post-thumbnails', 'revisions' ) ) ); } add_action('init', 'post_type_profiles');
add_filter('post_type_link', 'custompost_permalink', 1, 3); function custompost_permalink($post_link, $id = 0, $leavename) { global $wp_rewrite; global $wpdb; $post = &get_post($id); if ( is_wp_error( $post ) ) return $post; $newlink = $wp_rewrite->get_extra_permastruct('custompost'); $sql = " SELECT city FROM anydatabase WHERE post_id = " . $post->ID . ""; $address = $wpdb->get_var($wpdb->prepare($sql)); $city = str_replace(" ", "-", strtolower($address)); $title = str_replace(" ", "-", strtolower(get_the_title( $post->ID ))); $newlink = str_replace("%city%", $city, $newlink); $newlink = str_replace("%postname%", $title, $newlink); $newlink = home_url(user_trailingslashit($newlink)); return $newlink; }
add_action('init', 'myposttype_rewrite'); function myposttype_rewrite($post_link) { global $wp_rewrite; $queryarg = 'post_type=custompost&p='; $wp_rewrite->add_rewrite_tag('%city%', '([^/]+)', $queryarg); $wp_rewrite->add_permastruct('custompost', '%city%/%postname%.html'); }
Perhaps theres any other solution, so let me know to use a variable from my database in the permalink. I work many days on it and it doesn’t work now! ??
- The topic ‘Use a variable in Custom Post Type permalink’ is closed to new replies.