Imrul.H
Imrul.H

Reputation: 5870

Passing a variable to template file in wordpress plugin

In my wordpress plugin I have a function which has a page id:

public function create_view_for_pdf() {
        $page_id = $_POST['page_id'];
        $this->template_shortcode('template.php');
    }

here, "template_shortcode" function includes a template located in a folder in the plugin directory.

private function KendoPdf_template_shortcode($template_name) {
        return include '/template/dir' . $template_name;
    }

In the template file, I want to pass the page id so that I can print content there. How can I do that?

Note: Since I am just including the template file, I thought I will get the $page_id variable there normally. But it did not work. I needed the page id in template file because the content will be different than the actual page. That page also has ACF fields. I am basically creating a new template for pdf export. That's why I cannot use all the content of that page.

Upvotes: 0

Views: 1336

Answers (1)

Blackbam
Blackbam

Reputation: 19366

Please correct me if I am wrong but why would you pass the the page_id to the template file if it is within $_POST? Just access the variable using $_POST['page_id']; within your template file.

Instead of including your template file you could also read it into a string with file_get_contents(); and do your desired replacements before you return it.

Another possibility would be a global variable which is already set: global $post;

And last but not least you could use output buffering with ob_start(); (and consecutive functions).

You see: A lot of ways to solve this.

Upvotes: 1

Related Questions