<?php
// Ensure MetaBox Relationships is loaded, manually require if needed
if ( ! function_exists( \'mb_relationships_get_connected\' ) && file_exists( WP_PLUGIN_DIR . \'/meta-box-relationships/meta-box-relationships.php\' ) ) {
require_once WP_PLUGIN_DIR . \'/meta-box-relationships/meta-box-relationships.php\';
}
// Custom permalink structure for City URLs based on relationships
function custom_city_permalink_structure($post_link, $post) {
if (empty($post_link)) {
return $post_link; // Return early if $post_link is not set
}
if (\'city\' === $post->post_type) {
// Ensure MetaBox Relationships functions are available
if (function_exists(\'mb_relationships_get_connected\')) {
// Get the parent County for this City using correct relationship type
$county = mb_relationships_get_connected(\'county-to-city\', array(\'to\' => $post->ID));
if ($county && is_array($county) && !empty($county)) {
error_log(\'County found: \' . $county[0]->post_name);
// Get the parent State for this County using correct relationship type
$state = mb_relationships_get_connected(\'state-to-county\', array(\'to\' => $county[0]->ID));
if ($state && is_array($state) && !empty($state)) {
error_log(\'State found: \' . $state[0]->post_name);
// Replace placeholders with actual slug values from the relationships
$post_link = str_replace(\'%state%\', $state[0]->post_name, $post_link);
$post_link = str_replace(\'%county%\', $county[0]->post_name, $post_link);
$post_link = str_replace(\'%city%\', $post->post_name, $post_link);
} else {
error_log(\'No state found for this county.\');
}
} else {
error_log(\'No county found for this city.\');
}
}
}
error_log(\'Generated post link: \' . $post_link); // Log the generated post link for debugging
return $post_link;
}
// Hook into wp_loaded to ensure all plugins are fully initialized before running the filter
add_action(\'wp_loaded\', function() {
add_filter(\'post_type_link\', \'custom_city_permalink_structure\', 10, 2);
}, 20);
// Add custom rewrite rule for City URLs
function add_custom_city_rewrites() {
// Rewrite rule for location/state/county/city
add_rewrite_rule(
\'^location/([^/]+)/([^/]+)/([^/]+)/?$\',
\'index.php?city=$matches[3]&county=$matches[2]&state=$matches[1]\',
\'top\'
);
}
add_action(\'init\', \'add_custom_city_rewrites\');
// Flush rewrite rules to ensure changes take effect
add_action(\'init\', function() {
flush_rewrite_rules();
});\'
\'
error_log(print_r(mb_relationships_get_connected(\'county-to-city\', array(\'to\' => $post->ID)), true));