php – What is the best way to define constant options for a theme?

Question

By constant options I mean properties of the theme that don’t change during every day use in production, but are changeable by the developer primarily for reusability purposes. Things like custom posts, sidebars, forms, custom features, etc.

There’s really two ways that I see as viable and both of them are used in WordPress core and base themes.

Constants

The first one of course is defining constants. The most obvious example of this is the settings in wp-config.php. WordPress uses these for mostly small and really basic definitions, such as the database configuration credentials and things like
define( 'ABSPATH', __DIR__ . "https://wordpress.stackexchange.com/" ); or define( 'WPINC', 'wp-includes' );.

Arguments inside functions

This is the way that I’ve been using for custom posts and such, and also the method WordPress uses for defining defaults for functions that take arguments, like wp_login_form(). It’s either a variable defined inside the function being hooked or the values defined right inside the function call.

add_action( 'init', 'register_my_post_type' );

function register_my_post_type() {
$labels = array( 'name' => __( 'my_post_type' ), 'singular_name' => __( 'My Post Type' ), ... );$args = array(
'labels' => $labels, 'public' => true, ... ); register_post_type( 'my_post_type',$args );
}


PHP supports defining arrays as constants since 5.6, so it could be possible to define these arguments. I think it would be nice if many of these options could be set in a separate file for simplicity.

Other methods, such as globals, static variables or singleton classes seem way overkill and also highly inefficient, so they’re off the table, but I’m not sure about constants.

So, would using constants like

define( 'MY_OPTION1', array(
'key' => 'value'
...
));


then using them like

add_action('init', 'my_function');

function my_function() {
some_function_that_takes_args( 'MY_OPTION1' );
...
}


be a bad idea? If yes, what is the correct/better way?

I have an impression that using constants might be a bad idea, though I’m not sure why or how bad. So what are some considerations in performance, usability, anomalies or other coding principles to consider?

0
7 months 2022-01-29T20:46:26-05:00 0 Answers 0 views 0