Customizing Rank Math URL

Please add the following code to functions.php of Child Theme


add_action('rank_math/vars/register_extra_replacements', function () {

rank_math_register_var_replacement(
'listingCat',
[
'name' => esc_html__('Listing Category', 'rank-math'),
'description' => esc_html__('Category of the current listing', 'rank-math'),
'variable' => 'listingCat',
'example' => wilcityRMPrimaryCategoryToListingCallback(),
],
'wilcityRMPrimaryCategoryToListingCallback'
);

rank_math_register_var_replacement(
'listingLocation',
[
'name' => esc_html__('Listing Location', 'rank-math'),
'description' => esc_html__('Location of the current listing', 'rank-math'),
'variable' => 'listingLocation',
'example' => wilcityRMPrimaryLocationToListingCallback(),
],
'wilcityRMPrimaryLocationToListingCallback'
);

rank_math_register_var_replacement(
'listingTag',
[
'name' => esc_html__('Listing Tag', 'rank-math'),
'description' => esc_html__('Tag of the current listing', 'rank-math'),
'variable' => 'listingTag',
'example' => wilcityRMPrimaryTagToListingCallback(),
],
'wilcityRMPrimaryTagToListingCallback'
);

});


function wilcityRMPrimaryCategoryToListingCallback()
{
$aDirectoryTypes = \WilokeListingTools\Framework\Helpers\GetSettings::getAllDirectoryTypes(true);
if (!is_singular($aDirectoryTypes)) {
return '';
}
global $post;
$category = wilcityChildGetPrimaryTerm($post->ID, 'listing_cat');
if (!empty($category)) {
return $category->name;
}

return '';
}

function wilcityRMPrimaryLocationToListingCallback()
{
$aDirectoryTypes = \WilokeListingTools\Framework\Helpers\GetSettings::getAllDirectoryTypes(true);
if (!is_singular($aDirectoryTypes)) {
return '';
}
global $post;
$location = wilcityChildGetPrimaryTerm($post->ID, 'listing_location');

if (!empty($location)) {
return $location->name;
}

return '';

}

function wilcityRMPrimaryTagToListingCallback()
{
$aDirectoryTypes = \WilokeListingTools\Framework\Helpers\GetSettings::getAllDirectoryTypes(true);

if (!is_singular($aDirectoryTypes)) {
return '';
}
global $post;
$tags = get_the_terms($post->ID, 'listing_tag');
if (!empty($tags) && !is_wp_error($tags)) {
$str = '';
$count = count($tags) - 1;
foreach ($tags as $index => $tag) {
if ($index == $count) {
$str .= $tag->name;
} else {
$str .= $tag->name.', ';
}
}

return $str;
}

return '';
}

function wilcityChildGetPrimaryTerm($post_id, $term)
{
$result = [];
if (class_exists('WPSEO_Primary_Term')) {
$wpseo_primary_term = new WPSEO_Primary_Term($term, $post_id);
$primary_term = get_term($wpseo_primary_term->get_primary_term());
if (!is_wp_error($primary_term)) {
$result = $primary_term;
}
}
if (!isset($result) || empty($result)) {
$terms = get_the_terms($post_id, $term);
if (!empty($terms) && !is_wp_error($terms)) {
$result = $terms[0]; //get the first category
}
}

return $result;
}

Leave A Comment?