1

I'm trying to create a few custom post types, and instead of hard-coding their names I just want to define them as a globally scoped variable. I thought I understood the scope but apparently not. The code below results in an error of Undefined variable:

$filmLabel = "Films";
$showLabel = "Shows";
function CreatePostTypes() {
    register_post_type( $filmLabel, GenerateFilmType($filmLabel));
    register_post_type( $showLabel, GenerateFilmType($showLabel));
}
add_action( 'init', 'CreatePostTypes' );

I've tried using $GLOBAL as well, with the same result. Can anyone spot what's wrong?

10
  • 2
    Why do you want to do this? Using global vars is generally bad practice. The accepted answer on this post gives a good explanation why.
    – vancoder
    Oct 12, 2021 at 17:17
  • @vancoder Generally I'm sure it is bad practice. Randomly hard-coding magic values everywhere is worse practice, I'm sure. That's why.
    – Fluxian
    Oct 12, 2021 at 19:16
  • 1
    See stackoverflow.com/questions/15687363/…
    – vancoder
    Oct 12, 2021 at 20:36
  • 1
    So the actual real reason why using globals is a bad idea is because of syntactically useless it is to do so. Cheers
    – Fluxian
    Oct 12, 2021 at 21:55
  • @Fluxian "Randomly hard-coding magic values" - a post type name/slug is not random. And it shouldn't change, otherwise all your data gets lost. Instead of the define() which seems a bit dated in modern PHP, I would simply go with a public class constant.
    – kero
    Oct 21, 2021 at 8:14

1 Answer 1

1

Globals are generally discourgaged. You can use define instead.

<?php
define("FILM_LABEL", "Films");
define("SHOW_LABEL", "Shows");
function CreatePostTypes() {
    register_post_type( FILM_LABEL, GenerateFilmType( FILM_LABEL ) );
    register_post_type( SHOW_LABEL, GenerateFilmType( SHOW_LABEL ) );
}
add_action( 'init', 'CreatePostTypes' );
2
  • Ah right. That's exactly what I was trying to do. Awesome!
    – Fluxian
    Oct 12, 2021 at 22:32
  • No problem, it's especially useful for storing app-keys, passwords and the like in wp-config.php ( assuming the wp-config.php is not publicly visible on github as that would defeat the purpose )
    – admcfajn
    Oct 12, 2021 at 22:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.