Chud37
Chud37

Reputation: 5007

Wordpress Custom Plugin: Can't use plugin vars

I've got the following custom plugin in wordpress, which I've activated in the dashboard:

<?php

/*
Plugin Name: Test Plugin
Plugin URI: http://google.net/contact-us
*/

    $me = array(
        "name" => "Randy Newman",
        "age" => 27,
        "bimbo" => "bongo"
    );

    echo "<h1>hellomum</h1>";

The <h1>hellomum</h1> outputs at the top of the page, so the script gets run, but I can't access the $me var in header.php. I've never written a wordpress plugin before, but ideally i'd like be able to pull information out another database (not the wordpress one) and display it on the page. How is it best to do this?

At the moment when I write <? var_dump($me); ?> in the header.php file i get NULL output, which isnt right as far as I can see.

Upvotes: 0

Views: 43

Answers (1)

Diego
Diego

Reputation: 1716

It's just a bit different from what you think, no worries. What is happening is that those variables that you declare in your plugin file doesn't freely become available in your theme. You need to find another way to do this.

First of all if you need another database you are going to need to setup a new connection to that database. If you need your data in your theme you could set up an "hook" for your plugin to use. For example in your header.php file (template one), use:

do_action('my_action');

then in your plugin you can do:

add_action('my_action','my_func_name');
function my_func_name(){
    // pull data from other db and print it to header.php
};

This is what we can give you as a starting point i guess

Edit: Since you asked for the possibility to return a value here's how to do the same thing but having a value to return:

In your template, instead of do_action use this:

$my_value_1 = apply_filter('my_filter_1',$first_arg,$second_arg,$third_arg);
$my_value_2 = apply_filter('my_filter_2',$first_arg);

To use those filters in your plugin you need instead of add_action, this other variant:

add_filter('my_filter_1','my_func_name1',10,3);
function my_func_name1($first_arg,$second_arg,$third_arg){
    // pull data from other db and print it to header.php
    return first_arg;
};

That is the case with multiple function arg, with single it is:

add_filter('my_filter_2','my_func_name2',10,1); // 10 is priority, 1 is accepted args
    function my_func_name2($first_arg){
        // pull data from other db and print it to header.php
        return first_arg;
    };

More documentation on those:

  1. https://developer.wordpress.org/reference/functions/add_action/
  2. https://developer.wordpress.org/reference/functions/add_filter/

Upvotes: 1

Related Questions