Hi @vipuljadvani,
To implement relative URLs throughout your WordPress site without unintentionally modifying the GUID field, you’ll need a targeted approach. The GUID
field should always remain an absolute URL because it is meant to serve as a unique identifier for posts. Here’s how you can adjust your setup:
1. Adjust the post_type_link
Filter
The post_type_link
filter can be used to make the permalink for custom post types relative, but this filter does not directly affect the GUID field unless another part of your code is overriding it. Ensure your filter function is specific to permalinks.
Here’s an improved implementation of the post_type_link
filter:
add_filter('post_type_link', 'convert_custom_post_type_links_to_relative', 10, 2);
function convert_custom_post_type_links_to_relative($permalink, $post) {
// Ensure the $permalink is an absolute URL and belongs to your site.
if (strpos($permalink, home_url()) !== false) {
$permalink = wp_make_link_relative($permalink);
}
return $permalink;
}
2. Ensure GUID is Not Modified
Verify that no other filter is modifying the GUID. A typical function modifying GUID might look like this:
add_filter('get_post_metadata', function($value, $object_id, $meta_key) {
if ($meta_key === '_guid') {
return null; // Ensure this returns null to avoid modifications to the GUID.
}
return $value;
}, 10, 3);
3. Use the wp_make_link_relative
Function
WordPress includes the wp_make_link_relative
function, which safely converts absolute URLs to relative ones. Use this function wherever you’re generating links (e.g., in templates, widgets, etc.) to ensure consistency.
4. Avoid Database Modifications
Instead of modifying the database directly, rely on filters to dynamically adjust URLs for display purposes. This approach ensures that the GUID and other sensitive fields remain untouched.
For example:
- Use
the_permalink
filter to ensure links in posts and pages are relative:
add_filter('the_permalink', 'make_permalink_relative');
function make_permalink_relative($permalink) {
return wp_make_link_relative($permalink);
}
When migrating between environments (e.g., development, staging, production), tools like WP Migrate DB Pro or DUPLICATOR can handle search-and-replace operations for URLs in the database. These tools avoid touching fields like GUID unless explicitly configured to do so.
Let me know if you face further issues.