给the_category的a标签添加class和data-hover


Updated on: September 1, 2020 in Wordpress by

//给 the_category的a标签添加class和data-hover

function add_category_callback( $result ) {

  $class = strtolower( $result[2] );
  $class = str_replace( ' ', '-', $class );
  // do more sanitazion on the class (slug) like esc_attr() and so on

  $replacement = sprintf( 'class="link link-light-primary size-14">%s</a>', $class, $result[2] );
  return preg_replace( '#>([^<]+)</a>#Uis', $replacement, $result[0] );

}

function add_category_slug( $html ) {

  $search  = '#<a[^>]+(\>([^<]+)\</a>)#Uuis';
  $html = preg_replace_callback( $search, 'add_category_callback', $html );

  return $html;
}

add_filter( 'the_category', 'add_category_slug', 99, 1 );

function add_hover_callback( $result ) {

  $class = strtolower( $result[2] );
  $class = str_replace( ' ', '-', $class );
  // do more sanitazion on the class (slug) like esc_attr() and so on

  $replacement = sprintf( 'data-hover="%s">%s</a>', $class, $result[2] );
  return preg_replace( '#>([^<]+)</a>#Uis', $replacement, $result[0] );

}

function add_hover_category_slug( $html ) {

  $search  = '#<a[^>]+(\>([^<]+)\</a>)#Uuis';
  $html = preg_replace_callback( $search, 'add_hover_callback', $html );

  return $html;
}

add_filter( 'the_category', 'add_hover_category_slug', 99, 2 );