How to display php function in WP shortcode - php

I should say that I am only starting my journey with PHP so probably that's why I can not do such a simple task.
I have got a simple php code which I need to use as a shortcode. I got no problem in make code for shortcode but what I cant understand is how to insert that php function inside. The php function I am trying to insert is:
$( element ).airport([ 'moscow', 'berlin', 'stockholm' ]);
And as a shortcode I made a such code:
function home_words_shortcode() {
return $element .airport([ 'moscow', 'berlin', 'stockholm' ]);
}
add_shortcode( 'home-words', 'home_words_shortcode' );
I did a research online and found what I thought similar to my code and tried to convert to circumstances but nothing seems to work.
Could anyone help me please.

Not sure why you want to add this script as a shortcode, but this could be a way:
function home_words_shortcode( $atts ) {
$atts = shortcode_atts( array(
'element' => '#default-element',
'cities' => '',
), $atts, 'home-words' );
$cities = json_encode(array_filter(explode(',', $atts['cities'])));
return "
<script>
jQuery('{$atts['element']}').airport($cities);
</script>
";
}
add_shortcode( 'home-words', 'home_words_shortcode' );
It works with a shortcode like:
[home-words element="#element" cities="moscow,berlin,stockholm"]

I'm not sure if I understand you, but this is not a php function:
$( element ).airport([ 'moscow', 'berlin', 'stockholm' ]);
As I can see, it's a jquery code, maybe you have problems with the selectors, you can get all the knowledge rigth here. And a example
I hope this will be useful for you.
PD: I'm not a native english speaker, so, be comprehensive please :)

Related

creating a variable shortcode based on user input that returns (prechosen) variables Wordpress

I need to update values in all posts of a wordpress installation on a regular base. I was gooing to use shortcodes to insert the request into the wordpress post. Then use a custom functions.php that holds all the variables that need to be updated from time to time.
I got it working. Somehow but not the way I intended to use it. I'm a total beginner. Please consider this when answering my questions.
I want to have a function that reads what comes after honda_ and displays the correct value in wordpress without having to create a separate shortcode for each variable.
When entering [honda_link] wordpress should display the value from honda_link. When entering [honda_longlink] the value from honda_longlink variable should get displayed. I don't want to create a shortcode for each value.
I came up with this as a working solution...
// Honda
function honda() {
$honda_link = 'www.honda.com';
$honda_longlink = 'http://www.honda.com';
$honda_free = 'Free';
$honda_new = '23.688 $';
$honda_mileage = '00';
return $honda_link;
}
add_shortcode('neu', 'honda_link');
I tried some approaches by using an array but it ultimately failed all the time. I also tried it with if statements but wasn't able to get the right value displayed.
Someone willing to help a noob? I think I need to see a working example in order to understand it. The code snippets I have been looking at (that do something similiar but not the same I want to achieve) did confuse me more than they helped me.
I came up with this / Which works in a way but... This isn't very comfortable to use.
add_shortcode('HONDA','HONDA_TEST');
function HONDA_TEST($atts = array(), $content = null, $tag){
shortcode_atts(array(
'var1' => 'default var1',
'var2' => false,
'var3' => false,
'var4' => false
), $atts);
if ($atts['var2'])
return 'honda2';
else if ($atts['var3'])
return 'honda3';
else if ($atts['var4'])
return 'honda4';
else
return 'honda1';
}
So now when using:
[HONDA var1="novalue"][/HONDA]
[HONDA var2="novalue"][/HONDA]
[HONDA var3="novalue"][/HONDA]
[HONDA var4="novalue"][/HONDA]
it shows:
honda1
honda2
honda3
honda4
and so on.
Is there a better way to achieve the intended goal from post #1 ? Any way I could import the $variables from 1st post in bulk for example?
I don't have a working WP setup right now to test, but could you try this:
add_shortcode('HONDA','HONDA_TEST');
function HONDA_TEST($atts = array(), $content = null, $tag){
$atts = shortcode_atts(array(
'model' => 1,
), $atts);
$myHondas = [1 => 'honda1', 'honda2', 'honda3'];
return isset($myHondas[$atts['model']]) ? $myHondas[$atts['model']] : 'unknown model id';
}
And use it with [HONDA model="1"], [HONDA model="2"]

Adding a Leaflet map based on php in Wordpress

I use a php-script within a plugin on a Wordpress-site to geocode an user-supplied address. After this I would like to visualize the point on a leaflet map. In order to do so I wanted to use the built-in functions from the leaflet-map plugin. I tracked down the class for this in the class.map-shortcode.php-file: Leaflet_Map_Shortcode. This class provideds the function shortcode. This is also added to the shortcode in Wordpress (Lines 135 onwards):
'leaflet-map' => array(
'file' => 'class.map-shortcode.php',
'class' => 'Leaflet_Map_Shortcode');
foreach ($this->_shortcodes as $shortcode => $details) {
include_once $shortcode_dir . $details['file'];
add_shortcode($shortcode, array($details['class'], 'shortcode'));
My Intention was using this in a straightforward way:
<?php
... some code for geocoding...
$coords = array("lng" => 11, "lat" =>43 );
$myMap= new Leaflet_Map_Shortcode;
$myMap->shortcode($coords);
?>
But nothing happens (i.e. nothing is displayed). So this leads me to several questions:
Why does this not work?
What's the best way of debugging this code?
Is there a better solution to my problem?
Turns out it is very easy due to a hint in the comments:
$mapPrint = $myMap->shortcode($coords);
echo($mapPrint);

Unable to put php code in return of shortcode

I need to hide the URLs of downloads in wordpress posts. I have found a great script to do this but it is not a plugin. I have installed the script and created a function to include it. I am not a pro with php at all.
However the script has a line to normally call it:
<a href="<?php downloadurl('http://yourdomainname.comdownloadables.zip','veryspecials'); ?>" >Your Downloadables</a>
I am not able to place this directly in posts so I am trying to make a shortcode for it, but I am getting stuck. The shortcode that I have is:
function secshort_func($atts, $content = null) {
extract(shortcode_atts(array(
"linkurl" => '#Download_Does_Not_Exist',
"linktitle" => 'Download',
), $atts));
return '<a href="<?php downloadurl(' .$linkurl. ','veryspecials'); ?>" >' .$linktitle. '</a>';
}
add_shortcode( 'secdown', 'secshort_func' );
I am getting errors when trying to run this, and through a process of elimination I know that it is from this part of the return code:
"<?php downloadurl(' .$linkurl. ','veryspecials'); ?>"
After searching the internet for solutions and trying everything that I can think of, I am completely stuck.
Any help would be very much appreciated - it is driving me crazy being stuck on such a little thing!
A few observations along with the answer:
Format your code. It makes life much easier when troubleshooting. Good indenting is huge (see below for your code, formatted).
Don't use cryptic / abbreviated function names. Type them out so that you create self documenting code.
It's better to not use extract. There are some who say it's OK, but it can create confusing code that is hard to troubleshoot because you don't know where a variable came from. It's preferable to explicitly set the variables. (In your case, because you use them only once, it's simplest to just reference them in the array form - $atts['link_url'])
You can call the function, but it has to be concatenated into the string (see below). Your code (and the other answer), are passing php into the string, rather than calling the function and passing the result into the string.
Formatted code, with answer:
// Use a clearer function name. No need for "func", that's implied
function download_link_shortcode($atts, $content = NULL) {
// Declare $defaults in a separate variable to be clear, easy to read
$defaults = array(
"link_url" => '#Download_Does_Not_Exist',
"link_title" => 'Download',
);
// Merge the shortcode attributes
$atts = shortcode_atts( $defaults, $atts );
// Concatenate in the results of the `download` function call....
return '' . $atts['link_title'] . '';
}
add_shortcode( 'secdown', 'download_link_shortcode' );
Try using double outer quotes and escape inner single quotes like this:
return "<a href=\'<?php downloadurl(\'" . $linkurl . "\',\'veryspecials\'); ?>\' >" .$linktitle. '</a>';

php sprintf not working as expected

$actions = array(
'EDIT' => sprintf('Edit',
'abf_cm',
'edit_course',
$item['course_id'],
'thickbox edit-box',
'edit_'.$item['course_id']
),
'DELETE' => sprintf('Delete','course_management','do_process','delete',$item['course_id']),
);
In doing so, the edit part is not being displayed.Am i doing anything wrong.
I also tried using the placeholders
'EDIT' => sprintf('Edit',
'abf_cm',
'edit_course',
$item['course_id'],
'thickbox edit-box',
'edit_'.$item['course_id']
),
but still no results. I also noticed that when i remove the class and id attributes in the earlier version, then it works fine.
Can you please give me a satisfactory explanation of this and tell me where am i doing wrong.
EDIT:
Im using this inside Wordpress for creating custom table using WP_List_Table class
function column_course_name($item ) {
//Build row actions
$actions = array(
'EDIT' => sprintf('Edit',
'abf_cm',
'edit_course',
$item['course_id'],
'thickbox edit-box',
'edit_'.$item['course_id']
),
'DELETE' => sprintf('Delete','book_management','do_process','delete',$item['course_id']),
);
//Return the title contents
return sprintf('%1$s%3$s',
/*$1%s*/ strlen($item['course_name'])>0?$item['course_name']:'<span style="color:silver">(No Name)</span>',
/*$2%s*/ $item['course_id'],
/*$3%s*/ $this->row_actions($actions) //row_actions is a method in this class
);
}
update:
Well, its strange to mention but the code works when i use a single class( ie when i delete the space between the two classes for the tag) .
Any thoughts?
Dipesh, maybe you have errors in the code around this snippet.
Try to check your code in isolation. I copied your code to the separate .php script with little set-up and checked $actions array with print_r, like this:
edit_array.php
<?php
$item = array();
$item['course_id'] = 1;
$actions = array(
'EDIT' => sprintf('Edit',
'abf_cm',
'edit_course',
$item['course_id'],
'thickbox edit-box',
'edit_'.$item['course_id']
),
'DELETE' => sprintf('Delete','course_management','do_process','delete',$item['course_id']),
);
print_r($actions);
I ran this script from console and got the following results:
$ php edit_array.php
Array
(
[EDIT] => Edit
[DELETE] => Delete
)
Generated link for $actions['EDIT'] is HTML valid, so one can safely conclude that your code itself is working fine, and error lies somewhere else.

wrong form_later() hook behaviour?

i'm using Drupal 6.19 , in order to do some changes to the forms i followed some tutorials on the web using the form_alter hook .
well identifying the form consist of testing $form_id (that worked fine) ,but adding new fields is done by manipulating the $form variable .
when i tried this on my code it didn't work ,so i tried to manipulate the $form_id variable instead and it worked !
i know that my problem is solved but i want to know what the difference between $form_id and $form ?
isn't $form_id suppose to store only the form identifier ? and the form content goes into $form ?
Since you're using Drupal 6 , you are using the wrong syntax for the hook_form_alter. What you have is the Drupal 5 syntax for the hook. This is what it should be...
hook_form_alter(&$form, &$form_state, $form_id)
Because you're using it the way you are, the $form_id variable IS actually the $form variable. Try swapping out to the correct one, and that'll help you out.
Here's a link to the documentation: Drupal API: hook_form_alter
ok, here is my code for the form_alter hook :
btw, i use dBug to view the content of variables (that's how i figured out that $form does'nt contain the form structure)
function testymodule_form_alter($form_id, &$form) {
include_once("dBug.php");
if ($form_id['#id']=='node-form') {
$form_id['testymodule_checkbox'] = array(
'#type' => 'checkbox',
'#title' => t('Newly testy Checkbox'),
);
new dBug($form_id);
}
this will add a new checkbox to the mentioned form (although it maniuplate $form_id not $form)
what i found on the net was manipulating $form :
function testymodule_form_alter($form_id, &$form) {
include_once("dBug.php");
if ($form_id['#id']=='node-form') {
$form['testymodule_checkbox'] = array( //here is the clue
'#type' => 'checkbox',
'#title' => t('Newly testy Checkbox'),
);
new dBug($form_id);
}
it's weird nan ?

Categories