• Resolved pshemek

    (@emmek)


    Hello,

    I’d like to adjust body_class a bit to get shorter custom page template CSS class (example: page-main instead of page-template-page-main-php).

    My code performs the task but I feel it is not the most efficient way. Could you show how to refactor it?

    /**
     * Adjust body classes
     */
    add_filter('body_class','my_template_class');
    function my_template_class($classes) {
      foreach ( $classes as $key => $class_name ) {
        if ( preg_match( "/page-template-.*-php/", $class_name ) ) {
          preg_match( "/page-template-(.*)-php/", $class_name, $matches );
          $classes = array_replace( $classes, array($key => $matches[1]) );
        }
      }
      return $classes;
    }

    Thank you.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    I think that’s pretty efficient. This will work also for the default page template which doesn’t have”-php” after the classname (“page-template-default”):

    add_filter('body_class','my_template_class');
    function my_template_class($classes) {
      foreach ( $classes as $key => $class_name ) {
        $classes[$key] = preg_replace( "/^page-template-(.*?)(-php|)$/", '$1', $class_name );
      }
      return $classes;
    }

    Thread Starter pshemek

    (@emmek)

    Great, thank you for the answer and assuring that my code is ok.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to improve body_class replacement with regular expressions’ is closed to new replies.