Body_class() function in Sage8

I’m trying to get my head around namespacing in Sage 8.

Can someone explain why body_class() can be called in base.php without prefacing with a namespace, but every other function in lib/extras.php requires calling with Extras/function() ??

<?php
namespace Roots\Sage\Extras;
use Roots\Sage\Setup;
/**
 * Add <body> classes
 */
function body_class($classes) {
  // Add page slug if it doesn't exist
  if (is_single() || is_page() && !is_front_page()) {
    if (!in_array(basename(get_permalink()), $classes)) {
      $classes[] = basename(get_permalink());
    }
  }
  // Add class if sidebar is active
  if (Setup\display_sidebar()) {
    $classes[] = 'sidebar-primary';
  }
  return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');

By all docs it seems body_class() should have to be called using Extras/body_class()

I also appear to be able to just delete the body_class function from Extras and I guess wordpress just uses this: https://developer.wordpress.org/reference/functions/body_class/

??

Would be great if someone can clear this up, or link me to relevant docs.

Cheers.

My understanding is that the body_class() function being called in base.php is the WordPress version of that function—the body_class() function found in lib\extras.php is only used to hook into the body_class filter, and modify the output of WordPress’s function, i.e. it’s not being called (directly) when body_class() fires in base.php.

If you want to re-write the “extras” version, you could refactor it to use an anonymous function, like so:

add_filter('body_class', function($classes) {
  // Add page slug if it doesn't exist
  if (is_single() || is_page() && !is_front_page()) {
    if (!in_array(basename(get_permalink()), $classes)) {
      $classes[] = basename(get_permalink());
    }
  }
  // Add class if sidebar is active
  if (Setup\display_sidebar()) {
    $classes[] = 'sidebar-primary';
  }
  return $classes;
});
1 Like