add_filter('post_type_link', 'custom_post_type_link', 10, 3);
function custom_post_type_link($permalink, $post, $leavename) {
if (!($post instanceof WP_Post)) {
return $permalink;
}
if ($post->post_type === 'movies') {
return get_home_url() . '/' . $post->post_name . '/';
}
return $permalink;
}
add_action('pre_get_posts', 'custom_pre_get_posts');
function custom_pre_get_posts($query) {
global $wpdb;
if (!$query->is_main_query()) {
return;
}
// Get the requested post name
$post_name = $query->get('name'); // Use 'name' instead of 'pagename'
if (empty($post_name)) {
return;
}
// Fetch post type from database
$result = $wpdb->get_row(
$wpdb->prepare(
"SELECT wpp1.post_type, wpp2.post_name AS parent_post_name
FROM {$wpdb->posts} AS wpp1
LEFT JOIN {$wpdb->posts} AS wpp2 ON wpp1.post_parent = wpp2.ID
WHERE wpp1.post_name = %s LIMIT 1",
$post_name
)
);
if (!$result) {
return; // Ensure we have a valid result
}
$post_type = $result->post_type; // Fix: Define $post_type
if ($post_type === 'movies') {
$query->set('post_type', $post_type);
$query->set('name', $post_name);
$query->is_single = true;
$query->is_page = false;
}
}