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...
Related
I have an application in TYPO3 CMS. It has an extension test_extension that has a controller and an action. This action should return some JSON.
class TestRequestController extends ActionController
{
public function testAction(): void
{
echo json_encode([
'test' => 123
]);
}
}
I want to be able to request this action via Postman. How can I do that? TYPO3 version - 8.7. Thanks in advance!
Creating Links
Usually extbase-extensions are created with the help of the extension extension_builder. This extension creates by default templates and links to open list- and detail-view.
It's possible to add additional actions and to create according links.
Also the usage of the templates is not required and your way to return the result of the action without usage of a template is possible.
The logic of the links is this, I break the parts down in single lines:
tx_extension_plugin[controller]=TestRequest
tx_extension_plugin[action]=test
There are still more parameters commonly used like id or search, but it's also possible to define individual parameters.
In your case the listed parameters seem to be sufficient and the link would look like this now:
www.example.com/?id=123&tx_extension_plugin[controller]=TestRequest&tx_extension_plugin[action]=test
for the extension news this would look like this, this is with your parameter-values which are not available in news. This example shows only how the extension-related part is handled (tx_news_pi1):
www.example.com/?id=123&tx_news_pi1[controller]=TestRequest&tx_news_pi1[action]=test
id is for the page here and not a parameter for your extension, else id had to look like this tx_extension_plugin[id]=123. So all extension related parameters have the form tx_extension_plugin[parameter]=value.
While it's possible to create those links with the API, it's easier to create them with the view helpers for the fluid templates. Note that sometimes an hash is added at the end, like this example: &cHash=1234567890.
The cHash-value you can't create without viewHelper or API, so the knowledge about the parameters and the other values is not enough to create the links.
Calling the link
Most often links are directly called by the browser and visible in the URL-bar. But sometimes and in your case you might call the links by AJAX, so that the json is loaded without being directly shown to the user.
It's also possible to wrap the json in script-tags, so that it's every time loaded when the whole page is called, it's not dynamic then and without AJAX it can't adjust to some user-interaction without loading a whole page again.
AJAX responses can be realized in many ways in TYPO3, the most easy one is to define a special page-type and a special page in the pagetree for it. On this page you add the plugin of your extension to return the json. This "Ajax-page" has to be configured to have the correct header for Json and must not return anything else but the JSON, so all HTML-Output has to be disabled.
I use a plugin (Popup Builder) on my WordPress site. Whenever I create a new popup with the plugin, it creates a shortcode for that popup. I want to call on that shortcode from within the theme functions.php file. But I can't seem to get it to work properly.
The shortcode runs only if conditions are met. And in this example it's when a visitor access the site for the first time. I then check for a certain cookie and if that cookie does not exist, the popup will fire up and force the visitor to choose one option from a list of options, and then the cookie will be set with the correct value, once they do.
However I cant seem to find a solution that fires the popup at all. An I also get this notice: Notice: do_shortcode_tag was called incorrectly. Attempting to parse a shortcode without a valid callback:
function check_for_cookies() {
// Check if cookie is already set
if(isset($_COOKIE['tln_valgt_fylke'])) {
// Do this if cookie is set
$string .= 'Hi, and welcome back!' ;
return $string;
} else {
// Do this if the cookie doesn't exist
$shortcode = do_shortcode("[sg_popup id=163]");
return $shortcode;
}
}
add_action('init', 'check_for_cookies');
What am I doing wrong, and what if this is not a good way of accomplishing what I want, then what is?
This is just a guess
But, I think its a timing issue. You are using the init action to hook into another plugins shortcodes. It's possible that plugin has not yet registered it's shortcode via add_shortcode or if it has registered it, it may not have "included" the file that defines the callback for it (for whatever reason).
In fact it seems likely because:
do_shortcode_tag was called incorrectly. Attempting to parse a shortcode without a valid callback
This indicates the shortcode was called and no callback existed for it. This is not a problem with your code per say. But it says that the plugin has not yet loaded the file that contains the callback.
You could test this by hooking into an action that happens later in the execution chain, after you know all plugins have been loaded and initialized. Like even wp_head
Perhaps you could even get away with changing the priority of the hook:
add_action('init', 'check_for_cookies', 20); //default is 10
This way it's triggered at the end of init, but even then it may be too soon. The only real way to know is to look at the code for the plugin and find out when it's registering it's "stuff". An easy way to do that is add this code to the plugins shortcode callback:
try{
throw new \Exception();
}catch(\Exception $e){
die("<pre>{$e->getTraceAsString()}</pre>");
}
This will throw and then catch an exception, and then output the stacktrace. Which may show you exactly where the shortcode is being setup. You'll have to trigger the callback (obviously) for it to work. You can also use print_r(debug_backtrace()) but it's much harder to read IMO.
PS I been doing a lot of WP work lately and I just had an issue with action timing ... lol. That was why I thought of it, I spent the last 2 days refactoring code. In my case I an replacing the add/edit/profile parts of the user system on both the front and back end. It's a sort of subuser plugin. And there is a lot of competing actions related to that if you know what I mean...
Well, I am developing a plugin a and I need to display some stuff from my plugin when TYPO3 page load.
Is there some function how to hook action, like in WordPress when page loads than plugin will execute some controller method? Then this controller will produce some output a HTML, which I would like to dispaly in frontend page. Specially I would like display custom script in the head. So the script should be like this <head>...<script>my content</script>...</head>
Ok, what you probably want to do is to develop a so-called TYPO3 extension - that's what plugins/add-ons are called in TYPO3 (which is the term you will likely find google results for).
To get started fast you can try the TYPO3 extension builder (https://docs.typo3.org/typo3cms/extensions/extension_builder/) - which can generate a skeleton extension for you.
For more information you can also have a look at https://docs.typo3.org/typo3cms/CoreApiReference/latest/ExtensionArchitecture/Index.html which explains the concepts in far more detail.
Additional information is available in https://docs.typo3.org/typo3cms/ExtbaseFluidBook/Index.html
in TYPO3 there is something named plugins, but you should differ to the meaning in other context.
first TYPO3 is a CMS which content is structured in a hierarchical tree of pages. These pages are the basis for navigation. and each page contains individual contentelmenents (CE).
As Susi already told: add ons to TYPO3 are in general 'extensions' which could extend(!) the functinality of TYPO3 in different ways. one way is the definition of (TYPO3-)Plugins. These are special ContentElements which enable to show special information.
While normal CEs have all the information what to show in the record (e.g. Text & Image), plugins can be more flexible.
typical examples are: show a list of records OR one record in detail.
These Plugins can be controlled with typoscript or the plugin-CE could have additional fields to hold information what to display.
For detailed information how a plugin is defined consult the links given by Susi.
And be aware: for security reasons it is not possible to just execute a plain PHP file to echo any output. You need to register your plugin using the API, build your output as string and return the generated HTML as string to the calling function. For beginners the ExtensionBuilder will help you to generate a well formed extension which uses the API to register and output your data.
OK guys, thanks for your answers, but it was not very concrete. I found this solution, is not the best one, but it works! If anybody has better please share.
At first, you have to make a file for the class which will be called from the hook at location /your-plugin-name/Classes/class.tx_contenthook.php. Filename have to have this pattern class.tx_yourname.php Inside we will have a code with one method which will be called by the hook.
class tx_contenthook {
function displayContent(&$params, &$that){
//content of page from param
$content = $params['pObj']->content;
//your content
$inject = '4747474747';
// inject content on
$content = str_replace('</body>', $inject. '</body>', $content);
// save
$params['pObj']->content = $content;
}
}
And next, we have to call it on the hook. So Let's go to /your-plugin-name/ext_localconf.php and add there these two lines, which makes a magic and handles also caching.
// hook is called after caching
$TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output'][] = 'EXT:' . $_EXTKEY . '/Classes/class.tx_contenthook.php:&tx_contenthook->displayContent';
// hook is called before caching
$TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-all'][] = 'EXT:'. $_EXTKEY .'/Classes/class.tx_contenthook.php:&tx_contenthook->displayContent';
I hope this will help those who struggling with typo3.
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');
}
}
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.