On a given search result page I need to modify the link targets on specific results, like:
http://www.name.com/company/company
to http://www.name.com/company/
;http://www.name.com/company/something
to http://www.name.com/company/#something
;http://www.name.com/business/business
to http://www.name.com/business/
;http://www.name.com/business/somethingelse
to http://www.name.com/business/#somethingelse
;http://www.name.com/portfolio/projectname
to http://www.name.com/portfolio/
;Please notice that this is a multilanguage website and URLs might also come in the form of http://www.name.com/en/company/something-en
, where I will need to change it to http://www.name.com/en/company/#something
, and so on.
I believe this might be achieved using regular expressions with PHP but I am not skilled enough to write something solid from scratch.
Pratical example, change the following links inside the search-content
div
(links generated by the wordpress loop):
<div id="search-content">
<h3><?php _e( 'Search Results for', 'foundationpress' ); ?> <span>"<?php echo get_search_query(); ?>"</span>:</h3>
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class('blogpost-entry'); ?>>
<header>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
</header>
<div class="entry-content">
<?php the_excerpt(); ?>
</div>
</div>
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif;?>
</div>
Tbis is the function:
function processHref($input_url) {
$regex_one = '#http://([^/]+)/([^/]+)/([^/]+)#';
$regex_two = '#http://([^/]+)/([a-z]{2})/(.+)/([^-]+)#';
if(preg_match($regex_one, $input_url, $matches)) {
$domain = $matches[1];
$first = $matches[2];
$second = $matches[3];
}
elseif(preg_match($regex_two, $input_url, $matches)) {
$domain = $matches[1];
$lang = $matches[2];
$first = $matches[3];
$second = $matches[4];
}
$output_url = "http://$domain/";
if(isset($lang)) $output_url .= "$lang/";
if(isset($first)) $output_url .= "$first/";
if($first != $second && $first != "portfolio")
$output_url .= "#$second";
return $output_url;
}
?>