In my inc/contact-form-processor.php files I set
$form_complete = FALSE;
in my template-contact.php file I have
<?php
/*
Template Name: Contact Page
*/
?>
<?php require_once 'inc/contact-form-processor.php'; ?>
<?php get_header();
$SidebarPosition = sidebar_position()[0];
$IndivSidebarPosition = sidebar_position()[1];
$DefaultSidebarPosition = sidebar_position()[2];
?>
<div class="container">
<div class="row">
<?php if ( $SidebarPosition == 'left' ) {
get_template_part( 'layouts/contact/left', 'sidebar' );
}
if ( $SidebarPosition == 'right' ) {
get_template_part( 'layouts/contact/right', 'sidebar' );
}
if ( ( $IndivSidebarPosition == 'none' ) || ( $IndivSidebarPosition == 'default' and $DefaultSidebarPosition == 'none' ) ) {
get_template_part( 'layouts/contact/no', 'sidebar' );
}
?>
<?php echo $IndivSidebarPosition = sidebar_position()[1]; ?>
</div>
</div>
<?php get_footer(); ?>
I thought that by using require once and then referencing the contact-form-processor file $form_complete would be available in this file and the subsequent default
get_template_part( 'layouts/contact/right', 'sidebar' );
which displays a contact form based on the condition
<div id="contact_form">
<?php if($form_complete === FALSE) { ?>
<form>
.. Form ...
</form>
<?php } ?>
</div>
However, the form is not displayed and when I check for the $form_complete variable it is empty. How can I pass the variable through to both the files, I have read that I can use
You can use the WordPress locate_template function within PHP’s
include(). It’s done like this:
include(locate_template('your-template-name.php'));
All of the variables available in your current script will be available in that
template file now too.
But I am not sure which file that code goes in and which file it is suppose to reference.
your issues relate to scope. There is no magic trick to the snippet
include(locate_template('your-template-name.php'));
Locate template just returns the filename (it looks in the theme to find the appropriate file, generally used for allowing overwriting by child themes). What is relevant to you is include will load the file into the same scope as the function/ line that called it.
So lets look at this:
$a= 'im outside scope';
$b = 'im outside scope but get passed into the function so i can be used';
function sample($var){
$c= 'in scope';
$d= $var;
include 'template.php';
}
sample($b);
Template.php
<?php
echo $a; // ''
echo $b; // ''
echo $c; // 'in scope'
echo $d; // 'im outside scope but get passed into the function so i can be used'
So if you use get_template_part(), this is a function, only variables you have passed into the function (either in the arguments, by calling globals, class props) will be available in the template, get template part does not accept arguments you can use for this.
So the solution is to replace your get_template_part() calls with include calls. This way you have variables in the same scope.
Related
First of all I should say this code is a sample and i remake for you to show what i want my original code too huge and can't post here, but the logic and functions similar to this example.
I made a dynamic title in a function called getTitle() and it show on #side-bar now i want to use this title in h1 tag too, but as you see h1 tag rendered before this function, and i'm not able to move h1 tag after #side-bar. Now i want to know how can i echo a variable that generated from a function, before call this function.
PHP:
<?php
function getTitle(){
global $title;
// some code to generate dynamic title
$title = "example title";
echo $sample = "123";
return $title;
// other code
}
?>
HTML:
echo <h1><?=$title;?></h1>;
<div id="side-bar"><?php getTitle(); ?></div> <!-- call -->
I know if i move $title after calling the function getTitle(); it works fine but i need to echo $title before calling this function. Is it possible? or any idea, or logic to do this?
Also i know i can clone the title from side-bar to h1 with javascript or etc.. but this is a h1 tag and can't fill it after page load in client side.
PHP:
<?php
function getTitle(){
// some code to generate dynamic title
return ['title' => 'Example title', 'sample' => '123'];
}
?>
HTML:
$response=getTitle();
echo <h1><?=$response["sample"];?></h1>;
<div id="side-bar"><?php $response["title"]; ?></div> <!-- call -->
Your approach is wrong. Instructions are not executed after return statement.
PHP function
<?php
function getTitle(){
$title = /*generate dynamic title*/;
return $title;
}
?>
HTML
<?php $generatedTitle = getTitle(); ?>
<h1><?php echo $generatedTitle; ?></h1>
<div id="side-bar"><?php echo $generatedTitle; ?></div>
I am trying to build a wordpress-like plugin for my own CMS using str_replace. So when user saves something like '[do_something]' into page content, it will be replaced by a prebuild function.
example:
<?php function do_something() {
// search database and display something
}
<?php
echo str_replace("[do_something]","<?php do_something(); ?>",$page_content);
?>
However using echo it returns
"<?php do_something(); ?>"
as text instead of php script and fails to execute.
Any suggestion?
UPDATED
So finally, I have come up with this:
function plugin($page_content){
$plugins = array(
'[function1]' => 'function1();',
'[function2]' => 'fucntion2();'
);
foreach($plugins as $plugin => $function) {
if (strpos($page_content, $plugin) !== false) {
eval($function);
break;
}
}
}
:)
Try this:
<?php
eval(str_replace('[do_something]', 'do_something();', $page_content));
?>
But please remember that using eval especially with user's input is a very bad practise.
I am having problem setting a variable in PHP for multiple use into if statements.
Although there are many files in my layout but these are the 3 files relevant to this issue:
session.php (it is actually a JavaScript function which determines the browser-width of the visitor which is included in my javascript file and I call this via an ajax call. However since that is irrelevant to this issue hence to avoid confusion and too much code on this page I am avoiding that file.)
<?php
session_start();
$_SESSION['layoutType'] = $_REQUEST['layoutType'];
?>
core.php
<?php
session_start();
if (empty($_SESSION['layoutType'])) {
echo '<script type="text/javascript"> var session=false; var layoutType;</script>';
} else {
echo '<script type="text/javascript"> var session=true; var layoutType=' . $_SESSION['layoutType'] . ';</script>';
}
$layout = 'normal';
if (!empty($_SESSION['layoutType'])) {
$layoutType = $_SESSION['layoutType'];
if ( $layoutType <= 219 ) {
$layout = 'minimal';
} else if ($layoutType >= 220 && $layoutType <= 1024 ) {
$layout = 'small';
} else {
$layout = 'normal';
}
$_SESSION['layout'] = $layout;
}
index.php
<?php
include ('core/core.php');
// Function to load all the JavaScript files
getJS();
echo '<div>Your browser width is: ' . $_SESSION['layoutType'] . ' and Value of $layout variable currently is <strong>'.$layout.'</strong></div>';
if ($layout = 'normal') { ?>
<?php echo '<strong>' . $layout . '</strong> is the value of $layout in session'; ?>
<div id="sidebar">
<p>Widgets go here</p>
</div>
<?php } ?>
The output
Even though, The layout-width falls in the small category (Your browser width is: 872 and Value of $layout variable currently is small), it is still displaying the bit which it should display only is the layout-widthe category is normal (normal is the value of $layout in session).
Typically what is hapenning here is the value of $layout is being overwritten by the if statement in the index.php file.
What I am looking for?
Along with layoutType I also want the value of $layout to be set in the session based on the logic in core.php. So that I can use it multiple times across the website in various if statements.
This is very important because these are varioys widgets / content in my layout which I want to load / not-load depending on the device of my visitor. Hence almost all the widhets wil be wrapped into an if statement.
Kindly help.
if ($layout = 'normal') { ?>
Evaluates to true because it's an assignment (use == or === instead). You can find more information about the Comparison operators in the PHP manual.
I have a header.php I'm loading in my controllers for every page. However I want to have dynamic titles for each page. My idea was to pass a $title variable into the view as I'm loading it:
//Home Controller
function index()
{
$data['title'] = "Dynamic Title";
$this->load->view('header', $data);
$this->load->view('layouts/home');
$this->load->view('footer');
}
and then check for the $title variable in my header.php
<title>
<?php if ($title)
{
echo $title;
}
else
{
echo 'Default Title';
}
endif; ?>
</title>
However this doesn't work and I get a blank page. I think it is my syntax for the header.php but I can't figure out why.
Proper if Syntax
Your syntax on the if-statement is a bit off. You can use either:
if (condition) {
// do a
} else {
// do b
}
Or
if (condition) :
// do a
else :
// do b
endif;
You seem to have transposed the ending of the latter onto the former.
Using the Ternary Operator in Title
Once you've made that change, your title can be printed as easily as:
<title><?php echo isset($title) ? $title : 'Default Title' ; ?></title>
Alternative View Loading
Another method of loading views is to work with a single template file:
$data['title'] = 'Foo Bar';
$data['content'] = 'indexPage';
$this->load->view('template', $data);
This loads the template.php file as your view. Within this file you load your subsequent parts:
<?php $this->load->view("_header"); ?>
<?php $this->load->view($content); ?>
<?php $this->load->view("_footer"); ?>
By no means is this necessary, but it may help you maintain brevity in your controller.
Well I would try doing a var dump of $title in the view, just to see if it's getting passed at all.
Also, you don't need "endif;" since you're ending the if statement with the last curly brace.
I have simple template that's html mostly and then pulls some stuff out of SQL via PHP and I want to include this template in three different spots of another php file. What is the best way to do this? Can I include it and then print the contents?
Example of template:
Price: <?php echo $price ?>
and, for example, I have another php file that will show the template file only if the date is more than two days after a date in SQL.
The best way is to pass everything in an associative array.
class Template {
public function render($_page, $_data) {
extract($_data);
include($_page);
}
}
To build the template:
$data = array('title' => 'My Page', 'text' => 'My Paragraph');
$Template = new Template();
$Template->render('/path/to/file.php', $data);
Your template page could be something like this:
<h1><?php echo $title; ?></h1>
<p><?php echo $text; ?></p>
Extract is a really nifty function that can unpack an associative array into the local namespace so that you can just do stuff like echo $title;.
Edit: Added underscores to prevent name conflicts just in case you extract something containing a variable '$page' or '$data'.
Put your data in an array/object and pass it to the following function as a second argument:
function template_contents($file, $model) {
if (!is_file($file)) {
throw new Exception("Template not found");
}
ob_start();
include $file;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
Then:
Price: <?php echo template_contents("/path/to/file.php", $model); ?>