I have a PHP class with methods that I would like to use anywhere I choose on my theme.
For instance this class:
<?php
class MyClass
{
const constant = 'constant value';
function showConstant() {
echo self::constant . "\n";
}
}
$class = new MyClass();
$class->showConstant();
?>
How would I include such a class in my theme?
You have a couple of ways to go about this; you can write a plugin, which might be a bit overkill, but you can also:
1
In your
functions.php-file, just add your functions there, and then you can call them in your theme2
Create a new directory in your themes folder, something like
/includes. Put your class in there. Then wherever in your theme where you need your class and it’s functions, just include it in your template:It all depends on what kind of class it is, what it does and how often you use it. There are a whole lot of ways to do it.