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?
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: <?
Use the Code Snippets Plugin The Code Snippets plugin is a great way to add custom code to WordPress sites, and is easier than creating your own plugin. It basically serves the same purpose as your own plugin, as custom code can be added without using your theme and in an upgrade-safe way.
To add external CSS and Javascript, first enqueue the script or style using wp_enqueue_script() or wp_enqueue_style(). You should load the style using wp_enqueue_style instead of loading the stylesheet in your header. php file.
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 theme
function myClassFunction() {
class MyClass {
const constant = 'constant value';
function showConstant() {
echo self::constant . "\n";
}
}
$class = new MyClass();
$class->showConstant();
}
2
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:
<?php
require_once('includes/MyClass.php');
$class = new MyClass();
$class->showConstant();
?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With