drupal_set_title not setting $title variable - php

I'm trying to use drupal_set_title in my node.tpl.php but the text I'm setting the title to is only showing up in the $head_title variable and not the $title variable. The $title variable is still set to the node's title.
This is in Drupal 7. I've used drupal_set_title multiple times like this in Drupal 6 and it has worked perfectly.

I think the reason this isn't working is because of where you're calling it from. Drupal's templating system works by building up variables (of which $title is one) and passing them in to the template file.
By the time you get to node.tpl.php the $title variable, which is only available in the scope of that file, is already set in stone. So while calling drupal_set_title will work to change the $head_title for html.tpl.php (which is called later than node.tpl.php, it can't change the variables of the template file you're calling the code from.
Your best bet would be to put a preprocess function in your theme's template.php which sets the title before the template file is processed:
function MYTHEME_preprocess_node(&$vars) {
drupal_set_title('A new title');
}
If that still doesn't work try explicitly setting $vars['title'] = 'A new title';` in the same preprocess function.
The best option would be to write a very small custom module and implement hook_node_view() which is called way before the template file comes into the process and should always work:
function MYMODULE_node_view($node, $view_mode, $lang_code) {
drupal_set_title('A new title');
}

Clive got me pointed in the correct direction, but I couldn't get the preprocess_node to work, so I had to use preprocess_page instead. Here's the code that works:
function mycooltheme_preprocess_page(&$vars){
if (isset($vars['node']) && $vars['node']->type == 'news'){
drupal_set_title('News');
}
}

Related

Smarty: How to read a {$var} stored in the database?

I use codeigniter with smarty.
I have a variable stored in the db called $serverName. I want to expand it to its actual value "Pedrosite". But when the page is loaded, it displays exactly {$serverName} and not the value.
So I found this solution on stackoverflow, using smarty's fetch function:
$data['content'] contains the text from the database.
$data['content'] = $this->CI->smarty->fetch('string:'.$data['content']);
With that, I can display the smarty vars, like: {$smarty.const.FCPATH}
But none of my custom $vars while they can be shown in a regular template (.tpl).
So I found this workaround that looks very hacky to me:
$this->CI->smarty->assign('serverName', $this->CI->config->item('server_name'));
I can put this in one of my __construct function and then it will affect the whole site, and then it loads properly. But I'm not sure it's the right way to proceed at all.
I don't really understand your question, but, if you have your variable $serverName and it content "Pedrosite" you can display it like that :
$this->smarty->assign('serverName' , $serverName);
$this->smarty->view('/modules/xxxxxx');
And display it in your .html file for example :
<p>{$serverName}</p>

Call php function in content in custom page in wp-admin

I editing custom page in wp-admin. Currently in editor i see that
[vc_column_text]Titile1[/vc_column_text]
After each [/vc_column_text] i need to display some info from database. How i can call php function with some parameters in wp-admin editor ?
Like this or so:
[vc_column_text]Titile[/vc_column_text]
[getInforFromDatabase('Titile1')]
This will take quite some doing. You just may not directly call a PHP function from within the WP-Admin Editor but you can create a simple, rudimentary Plugin to do the heavy-lifting for you. And then expose a short-code that you can use from within the WP Admin Editor.
To do this, first create a a Directory in your wp-content/plugins directory. For the purposes of demonstration, we will call this directory: dbInfoSifter but the name is completely up to you. In the end, the path to this directory would be: wp-content/plugins/dbInfoSifter
Now inside of this Folder (dbInfoSifter), create a PHP File with the same name again so that you have: wp-content/plugins/dbInfoSifter/dbInfoSifter.php. Now add the following Code inside the dbInfoSifter.php File:
<?php
/*
Plugin Name: DB Info Sifter
Plugin URI: your-domain.tld
Description: Simple Plugin to sift data From Database.
Author: Your Name
Author URI: http://your-domain.tld
Version: 1.0.0
*/
// THE COMMENTED LINES ABOVE INFORMS WORDPRESS THAT THIS IS A PLUGIN.
// SO IT KNOWS TO ADD IT TO THE PLUGINS LIST...
// WE SHALL REVISIT THIS SOONER THAN LATER...
// IN THIS FILE YOU SHOULD PUT ALL THE LOGIC
// FOR GETTING DATA FROM THE DATABASE OR DOING ANYTHING AT ALL
// HOWEVER, THE MOST IMPORTANT THING IS TO EXPOSE THE SHORT-CODE
// SO THAT WE CAN USE IT INSIDE THE WP-ADMIN EDITOR.
// WE CAN DO THAT WITH THE FOLLOWING LINES OF CODE...
add_shortcode('getInfoFromDatabase', 'dbsGetInfoFromDatabase');
// THE LINE ABOVE EXPOSES THE SHORT-CODE SO THAT YOU CAN CALL IT
// FROM YOUR WP-ADMIN EDITOR... THE ARGUMENTS ARE SPECIFIC:
// THE 1ST ARGUMENT IS THE NAME OF THE SHORT-CODE
// THE 2ND IS THE NAME OF THE FUNCTION TO RUN WHEN THIS SHORT-CODE IS CALLED.
// SO NOW, WE WRITE OUT THE FUNCTION ITSELF:
//THE $atts PARAM IS AN ARRAY OF PARAMETERS PASSED TO THE SHORT-CODE.
function dbsGetInfoFromDatabase($atts){
extract( shortcode_atts( array(
'title1' => "default_value", /*<= SET DEFAULT VALUE*/
'param2' => "default_value", /*<= SET DEFAULT VALUE*/
), $atts ));
// WITH THE extract FUNCTION YOU CAN NOW USE title1 AND param2
// AS NORMAL VARIABLES IN YOUR PROGRAMS LIKE $title1, $param2.
// SO THIS IS WHERE YOU BUILD YOUR LOGIC TO GET DATA FROM THE
// DATABASE & YOU CAN USE THE PARAMETERS TOO...
// YOU ARE NOT LIMITED TO THE NUMBER OF PARAMETERS TO USE
// AS WELL AS THE NAME OF THE PARAMETERS...
// THOSE ARE COMPLETELY UP TO YOU...
/* AND SO; YOUR LOGIC CONTINUES...*/
// IT IS HIGHLY IMPORTANT THAT THIS FUNCTION RETURNS A VALUE.
// MOSTLY LIKELY, THE TYPE WOULD BE A STRING
// (ESPECIALLY IF YOU WANT TO DISPLAY IT AUTOMATICALLY)
return $stringValueResultingFromDBTransactions;
}
That's all... nothing really special to it... But you can also have other Functions within this File that does something, anyways. However, the most important parts of this File (in your case) are: 1.) The function: dbsGetInfoFromDatabase($args) and 2.) The Comments at the Top of the File.
Now, inside the WP-Admin Editor; you can just simply reference this function using the short-code we created like so:
// WP-ADMIN EDITION (BACKEND)
[vc_column_text]Titile[/vc_column_text]
[getInfoFromDatabase title1='Titile1'] //<== CALL YOUR SHORT-CODE
Alternatively, You can do it like so:
//WP-ADMIN EDITION (BACKEND)
[vc_column_text]Titile[/vc_column_text]
[getInfoFromDatabase title1='Titile1'][/getInfoFromDatabase]
Both will achieve the same Result, but the First one seems more concise (to me). Take your pick.
Finally, you need to activate the Plugin at the Backend for this to work. So; navigate to your Plugins Section (at the Backend of Wordpress). You will notice a new Plugin called DB Info Sifter. Simply activate it and you are finally ALL DONE. Your short-code would now work as if you actually called a function and passed it the $title1 parameter.
I hope this helps you a little bit and gives you a head-start...
Good-Luck to you, my Friend...

include typoscript with php

Is it possible to include a typoscript file via php?
Normally I would include typoscript with this:
<INCLUDE_TYPOSCRIPT: source="FILE:fileadmin/templates/typoscript/setup/1.ts">
But I want to do this just with php and not typoscript. Is that possible?
My Purpose: I want to dynamically load typoscript in my page
This can be achieved by invoking accordant functions at an early stage, e.g. in calling or delegating it in ext_localconf.php. For example, the bookstrap package is loading TypoScript in PHP like this:
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPageTSConfig(
'<INCLUDE_TYPOSCRIPT: source="FILE:EXT:' . $_EXTKEY
. '/Configuration/PageTS/Mod/Wizards/newContentElement.txt">'
);
Please consider, that TypoScript is cached before the actual front-end rendering starts. This means, that you should not modify TypoScript if you're plugin class or controller logic has been called already.
May be you need to return a value from the php function and use typoscript conditions for choosing the typoscript file.
You might try the following (if I get you right):
$typoscriptFile .= file_get_contents($someFile);
$parser = t3lib_div::makeInstance('t3lib_TSparser');
$parser->parse($typoscriptFile);
$tsArray = $parser->setup;
I really don't know how well that will play with anything related to global typoscript though.
If you wanted a complete correct parse, you might be able to pull something like this off if you populated a fresh t3lib_TStemplate instance from $GLOBALS['TSFE']->tmpl and than ran the code above. Might work, never tried.

Where to put my custom functions in Wordpress?

I am pulling my hair out. I have created some simple functions that generate random numbers, pulled from a database that I want to use on wordpress pages. (And then call them from the theme files, such as header.php or page.php.)
I have tried putting the functions inside functions.php that is in the theme (as per the documentation I have read), but I keep getting the "call to undefined function" errors! What in the world am I doing wrong?
Example, here is a function inside the functions.php
function randomPollNumber() {
///this gets a random active poll number
$sql12 = "SELECT id FROM poll WHERE removed = 0 AND active = 1 ORDER BY RAND() LIMIT 1";
$result12 = mysql_query($sql12);
$myrow12 = mysql_fetch_row($result12);
$pollquestionid = $myrow12[0];
return $pollquestionid;
}
And I am calling it, from the header.php file with this
<?php echo randomPollNumber(); ?>
And yes, I DID try using the if_function_exists, but of course it cannot FIND the function, so of course it does not exist. Please help?
Very strange - some debugging tips:
Put die('functions.php file loaded') statement at the beginning of functions.php (not inside a function). If it doesn't die, you know the file isn't being loaded.
If it dies, then check your spelling (copy and paste the function name from functions.php into your echo [...]). It's amazing how many times I'm SURE I've spelt it right, when in fact I haven't.
If it doesn't die, check that your file is definitely called functions.php, that it's definitely inside the right theme folder for the theme you are coding.
It's possible that the functions.php file has an error in it, and so is not being parsed, hence Wordpress can't find the function. Check your logs for errors. Load the functions file and nothing else, and check that the function is working. Are you using PHP Unit or something like that?

Using PHP variables inside body content area

I'm having trouble with using PHP code on my pages, within my body content area. I've searched tirelessly on this site, Drupal's site, and other sites in general, so I apologize if the answer is on this site somewhere, but I can't find it and I need help.
We have a lot of info we reuse throughout our site that I'd like to store in a PHP file as variables. We do this on our site now, but I'm rewriting our whole site to use Drupal. So, for example, we sell software, and I'd like a variable for each of our product URLs for various 'add to cart' buttons on the site. I don't want to have to hardcode the product URL into each link, but rather to seta PHP variable that I can call on any drupal page.
I cannot get anything to work; I've read about several suggestions but none work. I've tried setting the variables as their own block, then calling them from within a page when I create a new page. I can echo the variables on the pages but only within the block they are inside, I cannot call them and get them to echo from other blocks or content areas. I've tried using the global keyword (as per one suggestion) but that didn't work for me.
I hope this makes sense. Other info? I'm using Drupal 6.x, I do have PHP code enabled when creating pages, I do have the PHP filter module enabled, I can get PHP code to render so I know it's working, it's just not working where I need it to be.
I should say (if it's not obvious just from reading this!) I am a Drupal newbie so if anyone can help and try to explain their suggestion as plainly as possible for me, I'd really appreciate it!
Thanks in advance.
EDIT 3/15/11
To try to explain further, I'll post some sample code. I haven't done this yet because there isn't much to show yet, and I thought it might confuse the issue even more.
So, I've made a Drupal 'page' which is for our software trial downloads. The PHP variables that I want to set are for our download links; I want to set them in one place so that if, in the future, the download link needs to change, I only have to do so in one spot. You see, we have download links on various site pages. The same is true of our 'buy now' links. Here is the page code:
<p>Try [product] free for 30 days.</p>
<!--<p>[token_custom_ewintry]</p>-->
<p><?php global $ewintry; ?>Download for Windows PC</p>
<p><?php global $emactry; ?>Download for Mac OS X</p>
<p><?php global $ebbtry; ?>Download for BlackBerry</p>
<?php
$ebbtryprint = variable_get("ebbtry", "default");
print $ebbtryprint;
?>
<p>Download for Windows Mobile</p>
<p><?php global $ipewlstorelink; ?>iPhone, iPad, iPod touch owners: Download [product] on the iTunes App Store. You'll be able to create 10 cards for free to try [product] before you buy!</p>
For this sample I've left in everything I've tried. You'll see my calls to global variables, which never worked. I have the global variables defined in a custom block that I created and placed in my 'content top' region. I learned that apparently nothing from that region is actually accesible to my page's body content, because the calls never worked.
I have a custom token that I made yesterday with the Tokens module; it never worked, but then I read on a different post that by default, tokens are available in the body content area, and I need a special filter. I've yet to find a filter, and so I am not sure this solution will ever work.
I have my call to variable_get. Now, this did work. I have variable_set defined within my template.php page. My value does print using the print call above in my code sample. However, I looked at this page this morning and I don't think that's the answer I need. Because now I'll have to call variable_get on all my pages before I can print anything, right? And that doesn't solve the problem where I wanted to only have to set everything in one place to call anywhere. I tried putting the variable_get call in my custom block, but again I can't access anything in 'content top' from my body content area. The variable_get call prints the value in 'content top' but then it will not re-print below that in the content area.
So maybe that code will help someone to help me. I am going to look in detail at CCK now, as that's the only other suggestion I haven't tried. Thanks in advance if anyone can help.
If you're trying to set a global variable, and then use it within a function/method block, you need to use the global keyword on import:
<?php
// For some reason, this sometimes gives me problems
$foo = 'test';
// So I do this instead, they are equivalent
$GLOBALS['bar'] = 'test';
echo "<p>Global <br/> foo: $foo <br/> bar: $bar</p>";
function globalTest() {
global $foo;
echo "<p>globalTest() <br/> foo: $foo <br/> bar: $bar</p>";
}
globalTest();
function globalBarTest() {
global $foo, $bar;
echo "<p>globalBarTest() <br/> foo: $foo <br/> bar: $bar</p>";
}
globalBarTest();
?>
In action: http://jfcoder.com/test/globals.php
Prints:
Global
foo: test
bar: test
globalTest()
foo: test
bar:
globalBarTest()
foo: test
bar: test
I have always gotten in the habit of setting a global variable using $GLOBALS, I never have any issues doing it this way.
I would caution, though, that setting globally scoped variables is considered harmful (or at least unnecessary), since they are so easy to accidentally overwrite somewhere else in your code (by you and/or someone else).
Your stated approach in the description sounds quite messy; you should be using a database and let Drupal abstract how you organize, set and get the data from the datastore, instead of editing your files and hardcoding some links and data into a PHP file. This is what I'm thinking reading your description, which may not be fair, but I thought I needed to mention it.
EDIT
In Drupal, you can set global variables in the default/settings.php page using variable_set(), and then use variable_get() to get the variable by name.
http://api.drupal.org/api/drupal/sites--default--default.settings.php/6
variable_set('foo','bar');
http://api.drupal.org/api/drupal/includes--theme.inc/function/template_preprocess/6
function yourtemplate_preprocess (&$variables) {
$vars['foo'] = variable_get('foo');
}
EDIT 2
Note the source for the variable_set() function:
<?php
function variable_set($name, $value) {
global $conf;
$serialized_value = serialize($value);
db_query("UPDATE {variable} SET value = '%s' WHERE name = '%s'", $serialized_value, $name);
if (!db_affected_rows()) {
#db_query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, $serialized_value);
}
cache_clear_all('variables', 'cache');
$conf[$name] = $value;
}
?>
EDIT
Ok, here is what you can do:
/drupal-root/htdocs/sites/settings.php
Open the settings.php file and at the bottom, set your PHP variables using the $GLOBALS global variables, as so:
$GLOBALS['test1_variable'] = 'test 1 variable';
And then in your template (with the PHP Input Format selected):
<?php
echo "<p>This is my {$GLOBALS['test1_variable']}.</p>";
?>
Or...
<p>This is my short tag <?=$GLOBALS['test1_variable'];?>.</p>
And you should see your variable printed out on the page from the template code. Note the curly braces surrounding the $GLOBALS variable.
If you want to provide additional info that should go with some nodes, you should use CCK to create a content type, that has all the additional infos. With styling inside a template, you can archive almost anything.
If CCK is not siutable (in most cases, it is exactly what you want), you need to implement a _preprocess_ function. This would look like
function yourtemplate_preprocess_page(&$variables) {
$vars['my_custom_var'] = "hello"; //anything can go here
}
Now you have a $my_custom_var in your page-template file available.
Be sure to make yourself familiar with the template system of Drupal (if you haven't already).
It sounds like you are looking for the token_filter module.
My problem is that it isn't ready (in token module) for D7 yet.

Categories