Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a custom class in a Wordpress theme

Tags:

php

wordpress

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?

like image 670
Gandalf Avatar asked Jan 19 '13 11:01

Gandalf


People also ask

How do I use classes in WordPress?

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: <?

Can I use custom code in WordPress?

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.

How do I add an external CSS to WordPress?

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.


1 Answers

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.

like image 185
Marcus Olsson Avatar answered Sep 28 '22 07:09

Marcus Olsson