Why is my function in Wordpress not working? - wordpress

Why not work my function in wordpress?
My code
add_post_meta( $ids, 'price', $price, true );
$price_add = get_post_meta($id, 'price', true);
function myprice(){
if ($price_add != ' '){
echo $price_add." Euro";
}
else {
echo "None";
}
}
I try use if (isset($price_add)) but not work.
I want to show price introduced in or show text "None".

You are attempting to use a variable which is not "in scope". You might want to read the PHP manual page on variable scope.
A function is a reusable piece of code, with input and output, and in PHP variables are "scoped" (visible) to the function they are declared in. (The main exception is global variables, which are usually frowned on as they make code hard to read, reuse, and test; static variables and object members work a bit differently.)
In your case, you want a function which takes as input a price, and echoes that price if it is not an empty string (or, as you've written it, a single space); you might define that like this:
function myprice($price_to_display) {
if ($price_to_display != ' '){
echo $price_to_display." Euro";
}
else {
echo "None";
}
}
You then call that somewhere else, passing in the value you want to display, like this:
$price_add = get_post_meta($id, 'price', true);
myprice($price_add);
Note that I've named the variable in the function something different for clarity; you could call it $price_add, but that wouldn't make it connected to the other variable called $price_add in any special way.
[Edited to add...] In fact, you don't need to have a variable at all when you are calling the function - what you are providing is a value for the input parameter. So you could also write it like this:
myprice( get_post_meta($id, 'price', true) );

Related

Unable to hook into custom filter hook using add_filter()

I am very new to Wordpress Development so this question might be silly .May be I do not understand the concept of custom filters in Wordpress . So far I have used Wordpress's own filter hooks to change values like below :
add_filter('the_content', 'ffl_add_footer') ; // add footer to the blog content
I have just started learning about custom filters that you can code . So my understanding is you use apply_filters() to set up a filter hook to a value($var below) like below :
apply_filters('filter_tag' , $var ) ;
Later you hook into that filter and use a callback function to modify the value ($var) like below :
add_filter('filter_tag , 'callback');
Your callback would be like below :
function callback($var) {
//modify $var
return $var
}
So I was testing this understanding with a code like below :
function callback($var){
return ($var.'append');
}
$var = 'testing';
echo $var;
$var1 = apply_filters('custom_filter', $var);
add_filter('custom_filter' , 'callback');
echo $var1;
This echoes testingtesting while I was expecting testingtestingappend . The callback function doesnt seem to get called at all as I tried exit() inside the callback . Am I understanding this wrong or is there something wrong with my code ?
The problem is that you're calling add_filter after apply_filters has been executed. You need to call it earlier so your callback gets registered first, then apply_filters will execute it
For example (untested, but it should work):
function callback($var){
return ($var.'append');
}
add_filter('custom_filter' , 'callback'); // register the callback
$var = 'testing';
echo $var; // testing
$var1 = apply_filters('custom_filter', $var); // apply registered callbacks
echo $var1; // testingappend

Populating a custom field from the Wordpress Postie Plugin

I am using the Postie plugin to auto post from email on my Wp blog.
I am trying to populate two custom fields (mail_meta_from and mail_meta_replyto") with the "from" and "reply to" fields
add_filter('postie_post_before', 'add_custom_field');
//Get the "from" and "replyto" email details
add_filter('postie_filter_email2', 'get_emaildetails', 10, 3);
function get_emaildetails( $from, $toEmail, $replytoEmail) {
DebugEcho("step-01b");
DebugDump("from " . $from);
DebugDump("toEmail " . $toEmail);
DebugDump("replytoEmail " . $replytoEmail);
$fromField = $from;
$replytoEmail = $replytoEmail;
return $from;
return $replytoEmail;
function add_custom_field($post) {
add_post_meta($post['ID'], 'mail_meta_from', '$from');
add_post_meta($post['ID'], 'mail_meta_replyto', $replytoEmail);
return $post;
}
}
This has been driving me nuts for the past 2 days, and I have tried multiple variations of the above but with no success.
At the moment, I am getting the error
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'add_custom_field' not found or invalid function name in /home/sites/mysite.com/public_html/wp-includes/plugin.php on line 213
I try and learn from my mistakes, but I am not getting anywhere with this...
The default answer for help with this on the WP forum is to check out http://postieplugin.com/extending/.
Which I have... repeatedly.
Any help would be greatly appreciated!
You are defining the add_custom_field() function inside the scope of the get_emaildetails() function because it is within the curly braces. You should also consider using a more unique name for your function, or encapsulate it an an object namespace. The error you are getting indicates that when the apply_filter() is called for postie_post_before it can't find a function called add_custom_field(). Use the code below to properly scope the function, though note that you have some other syntax errors as well.
add_filter('postie_post_before', 'add_custom_field');
function add_custom_field($post) {
// the variable $from is not defined, and it will not evaluate if enclosed
// in single quotes. if you want the value of $from define it then use "{$from}"
add_post_meta($post['ID'], 'mail_meta_from', '$from');
// $replytoEmail is not defined
add_post_meta($post['ID'], 'mail_meta_replyto', $replytoEmail);
return $post;
}
//Get the "from" and "replyto" email details
add_filter('postie_filter_email2', 'get_emaildetails', 10, 3);
function get_emaildetails( $from, $toEmail, $replytoEmail) {
DebugEcho("step-01b");
DebugDump("from " . $from);
DebugDump("toEmail " . $toEmail);
DebugDump("replytoEmail " . $replytoEmail);
// what is this for?
$fromField = $from;
// setting to itself, then not used?
$replytoEmail = $replytoEmail;
return $from;
// this will never return?
return $replytoEmail;
}

Wordpress filter on adding meta?

In wordpress, I need to program it such that anytime someone enters or updates a post meta called "start_date", a bit of code is run on what is entered before it is saved.
I need to take what is entered and convert it to a unix timestamp.
Is there a way to do this?
If not, is there a way to add the code on publish or update of the post such that it checks for that meta and updates it if needed?
Assuming you're creating the metaboxes and custom fields with your plugin, you can do the following. Otherwise, it depends on how their saving the data as it could overwrite yours.
Here's something to get you started though depending on what the case is.
add_action('save_post', 'update_the_post_meta', 100, 2);
function update_the_post_meta($post_id, $post) {
if ( defined('DOING_AJAX') && DOING_AJAX ) { return; }
if ( defined('DOING_CRON') && DOING_CRON ) { return; }
if ($post->post_type == 'revision') { return; }
if ( isset($_REQUEST['start_date']) ) :
//do your timestamp code here and save it in $timestamp
add_post_meta($post_id, 'start_date', $timestamp, true) or update_post_meta($post_id, 'start_date', $timestamp);
else :
delete_post_meta($post_id, 'start_date');
endif;
}
Right now the priority of the add_action is set to 100 (the higher the number, the less priority it has). So, if you're trying to override someone else's function, you may need to increase the priority number. Also, this is assuming the name of the input field is "start_date".

Drupal 6 getting the node title from a submitted form

I am using form_alter to edit the submit function when editing content. In my custom function I wish to edit a custom message to the screen with the title name. I thought a way I could do this is something as follows
function mymodule_myfunction(&$form) {
drupal_set_message(t('Some text ' . $form['#node']->title));
}
The title is not being joined to the 'Some text'
I am calling my function by using the following line in my form_alter:
$form['#submit'][] = 'mymodule_myfunction';
All submit functions get two parameters passed to them: $form, which is the final form array after all of the adjustments for hook_form_alter and the like, and $form_state which among other values contains the submitted values, which have been cleaned and checked for ranges. (For instance, if you have three items in a select box, the data in $form_state['values'] already has made sure that the value for that input is one of the three legal values.)
Generally, you shouldn't use $form['#post'] - it's not part of the published way to get at values, and an update to the core to handle some problem with FAPI could conceivably break your code.
Try this:
function mymodule_myfunction($form, &$form_state) {
drupal_set_message(t('Some Message #title'),
array('#title' => $form_state['values']['title'])));
}
Note the corrected use of the t() function - the intent of that function is to allow other users to translate text, and so by using 'Some Message #title' the translator knows more about what is going on. Additionally you get the advantage that text fed through the t function in this way also is fed through check_plain(), which prevents someone from doing something malicious with the input.
DKinzer recommended using dsm($form)to see the variables. The Node title is not populated. It can be found in the Post array. The following line allowed me to do what I wanted.
drupal_set_message(t('Some Text '.$form['#post']['title']));
Try changing the signature of your
function mymodule_myfunction(&$form) {
drupal_set_message(t('Some text ' . $form['#node']->title));
}
To:
function mymodule_myfunction($form, &$form_state) {
drupal_set_message(t('Some text ' . $form['#node']->title));
}
Also try installing the devel module so you can do things like
dsm($form);
dsm($form_state);
And see exactly what you are dealing with.
Also, if all you want to do is give a message when a new node of type 'X' is created a better way is to use hook_nodeapi;
It could look something like this;
function modulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
if ($op == 'insert' && $node->type == 'my node type') {
drupal_set_message($node-title . ' is cool.');
}
}

How to override form action in Drupal?

I originally started this question in another thread, but that thread was sorta, kinda answered, and now I primarily want to know how to specify another form action... I tried using the code below, but the form action, when output, remains unchanged, although looking at the print_r($form), it's correctly changed... Why isn't it picking up?
function mytheme_user_profile_form($form) {
global $user;
$uid = $user->uid;
//print '<pre>'; print_r($form); print '</pre>';
$category = $form['_category']['#value'];
switch($category) {
case 'account':
$form['#action'] = '/user/'.$uid.'/edit?destination=user/'.$uid;
break;
case 'education':
$form['#action'] = '/user/'.$uid.'/edit/education?destination=user/'.$uid;
break;
case 'experience':
$form['#action'] = '/user/'.$uid.'/edit/experience?destination=user/'.$uid;
break;
case 'publications':
$form['#action'] = '/user/'.$uid.'/edit/publications?destination=user/'.$uid;
break;
case 'conflicts':
$form['#action'] = '/user/'.$uid.'/edit/conflicts?destination=user/'.$uid;
break;
}
//print '<pre>'; print_r($form); print '</pre>';
//print $form['#action'];
$output .= drupal_render($form);
return $output;
hook_form_alter() is likely the way to go.
Here are some hopefully helpful links:
Form Theming: How do I set $form['action']?
Modifying Forms in Drupal 5 and 6
hook_form_alter
EDIT: reply to comment #1 below:
How to implement hook_form_alter():
You must create a module (you cannot use template.php). It's easier than it looks.
For a module named "formstuff", you would create formstuff.info and formstuff.module and put them in either sites/all/modules or sites/yoursitename/modules. Set up the .info and .module files per the instructions, then just create the following function in your .module file:
function formstuff_form_alter(&$form, $form_state, $form_id) {
// do stuff
}
This function is a hook because it is named properly (i.e. replace the word 'hook' with the name of your module), and it matches hook_form_alter's function signature (i.e. it takes the same parameters).
Then just enable your module in your site's admin and the hook should do it's magic.
Note that hook_form_alter takes a reference to the form; this allows you to modify it in-place.
You need to put the form_alter function in a module and then use either if or switch to check the form ID. If the form ID is the one you want to alter then give the form an action property
$form['someID'] = array(
'#action' => 'path/you/want',
);

Resources