Jump to content

Anchor Tag with Repeaters


Joss
 Share

Recommended Posts

Here is a quickie!

If you use repeaters for sections on a page (good use for repeaters that) then you may want to use anchors to help navigation.

The most obvious thing to use is the "name" of the repeater, because repeaters are actually pages and the name field has no spaces.

Ah! But there is a problem with repeaters! They are stored as pages under admin, in your page tree, and if you go and look at one you will see that its "name" looks something like:

1401972317-1689-1

Which is less than useful.

The next thing to use is the "title" field, but that has spaces, uppercase and the rest.

So, here is a quick and dirty little function that I found on StackExcahnge

function seoUrl($string) {
    //Lower case everything
    $string = strtolower($string);
    //Make alphanumeric (removes all other characters)
    $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
    //Clean up multiple dashes or whitespaces
    $string = preg_replace("/[\s-]+/", " ", $string);
    //Convert whitespaces and underscore to dash
    $string = preg_replace("/[\s_]/", "-", $string);
    return $string;
}

Now all you have to do is use it in your foreach loop for your repeater:

function myRepeater (){
	$repeaters = wire("page")->my_repeater;
	$out = "";
	foreach($repeaters as $repeater){
		$anchor = seoUrl($repeater->title);
		$out .="<a name='{$anchor}'><h3>{$repeater->title}</h3></a>";
	}

	echo $out;
	
}

And there you have it. Your anchors are now-like-this and your SEO is just that tiny bit better.

Note: There is probably a neater way to do this, but this is nice and clear and does everything, I think.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...