So I'm still new to Wordpress and development in general and trying to add a leading zero to post pagination numbers. The code I came up with is as follows:
function leading_zero_wp_link_pages_link( $i ) {
$i = zeroise($i, 2);
return $i;
}
add_filter( 'wp_link_pages_link', 'leading_zero_link_pages_link' );
which of course isn't working. I know I need to modify the '$i' integer variable as specified in the codex and I'm almost certainly misunderstanding how hooks/filters work and any help would be great!
So I'm still new to Wordpress and development in general and trying to add a leading zero to post pagination numbers. The code I came up with is as follows:
function leading_zero_wp_link_pages_link( $i ) {
$i = zeroise($i, 2);
return $i;
}
add_filter( 'wp_link_pages_link', 'leading_zero_link_pages_link' );
which of course isn't working. I know I need to modify the '$i' integer variable as specified in the codex and I'm almost certainly misunderstanding how hooks/filters work and any help would be great!
wp_link_pages_link
filters the entire HTML link (<a href...
etc.), which is why what you've got isn't working. There doesn't appear to be a filter for just the page number, $i
, so you'll need a workaround.
Since the callback function for the wp_link_pages_link
filter passes the $i
, we could use that to find the number inside the HTML and replace it.
The simple version would be to simply replace $i
inside $link
:
function wpse_287783_zeroize_page_numbers( $link, $i ) {
$zeroised = zeroise( $i, 2 );
$link = str_replace( $i, $zeroised, $link );
return $link;
}
add_filter( 'wp_link_pages_link', 'wpse_287783_zeroize_page_numbers', 10, 2 );
There are two related problems with this solution:
So what we need to do is only replace the number inside the HTML tag. To do that we can use a regular expression:
function wpse_287783_zeroize_page_numbers( $link, $i ) {
$zeroised = zeroise( $i, 2 );
$link = preg_replace( '/>(\D*)(\d*)(\D*)</', '>${1}' . $zeroised . '${3}<', $link );
return $link;
}
add_filter( 'wp_link_pages_link', 'wpse_287783_zeroize_page_numbers', 10, 2 );
Now someone might be able to provide a better regular expression, since I'm rubbish at them, but what '/>(\D*)(\d*)(\D*)</'
does is get characters between >
and <
, which will be the stuff inside the tag, and return 3 things: Text before any digits, any digits, and text after the digits. The text before and after is so it still only affects digits if link_before
, link_after
or pagelink
from wp_link_pages()
have any other text in them.
With preg_replace()
we are replacing just the 2nd thing returned, the digits, with the zeroised version of the page number.