How to add SVG arrows to WP-PageNavi next and previous buttons

  • Code Snippet
  • WordPress
  • WP-PageNavi

Recently I needed to alter the HTML output of WP-PageNavi next and previous buttons to add custom SVG arrows. I struggled to find a decent solution, so I created one myself using the wp_pagenavi filter.

Drop this code into your functions.php file and amend the SVG code accordingly to suit your given arrow styling.

 

// Add arrows to WP-PageNavi next and previous buttons
function custom_wp_pagenavi_arrows($html) {
  // Find the 'nextpostslink' element in the HTML
  $next_pattern = '/(<a class="nextpostslink".*?>)(.*?)(<\/a>)/i';

  // Find the 'previouspostslink' element in the HTML
  $prev_pattern = '/(<a class="previouspostslink".*?>)(.*?)(<\/a>)/i';

  // Define the SVG arrows
  $next_svg_arrow = '<svg aria-hidden="true" viewBox="0 0 20 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10.8862 13.5934L16.1413 8.33832L0.561405 8.34021L0.561405 6.65979L16.1602 6.64276L10.9222 1.40467L12.0803 0.246534L19.3338 7.5L12.0632 14.7705L10.8881 13.5953L10.8862 13.5934Z" fill="black"/></svg>';

  $prev_svg_arrow = '<svg aria-hidden="true" viewBox="0 0 20 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.11466 1.40655L3.85956 6.66163L19.4395 6.65974L19.4395 8.34016L3.84066 8.35719L9.07866 13.5953L7.92056 14.7534L0.667058 7.49995L7.93766 0.229453L9.11276 1.40465L9.11466 1.40655Z" fill="black"/></svg>';

  // Replace the link text with the link text + SVG arrow for 'nextpostslink'
  $next_replacement = '$1$2' . $next_svg_arrow . '$3';

  // Replace the link text with the SVG arrow + link text for 'previouspostslink'
  $prev_replacement = '$1' . $prev_svg_arrow . '$2$3';

  // Apply the replacements to the 'nextpostslink' and 'previouspostslink' elements
  $modified_html = preg_replace($next_pattern, $next_replacement, $html);
  $modified_html = preg_replace($prev_pattern, $prev_replacement, $modified_html);

  return $modified_html;
}

// Hook your custom function to the 'wp_pagenavi' filter
add_filter('wp_pagenavi', 'custom_wp_pagenavi_arrows');

Let's build something great

Interested in starting your own website project with me? Excellent! I'd love to talk to you about your idea.

Get in touch

I aim to reply within 48 hours.