I have a very strange problem in my wordpress development,
in fucntions.php I have the following code
//mytheme/functions.php
$arg = "HELP ME";
add_action('admin_menu', 'my_function', 10, 1);
do_action('admin_menu',$arg );
function my_function($arg)
{
echo "the var is:".$arg."<br>";
}
the output is
the var is:HELP ME
the var is:
Why the function repeated 2 times? Why has the argument "help me" been passed correctly and the 2nd time it havent been passed?
I have been trying all my best for 2 days and searched in many places to find a solution but I had no luck.
What I am trying to do is simple! I just want to pass argument to a function using add_action?
Inside "my_function" (albeit it's yours :)), write line:
print_r(debug_backtrace());
http://php.net/manual/en/function.debug-backtrace.php
It will help you to know, what are going on.
Or, you can use XDebug (on development server).
Well, first off, in your my_function() function, you're not defining $arg. You're trying to echo something out that isn't there - so when it's returned, it's empty. So you need to define it. (edited to add: you're trying to define it outside the function - but to make the function inside recognize it, you have to globalize the argument.)
function my_function($arg) {
if(!$arg) $arg = 'some value';
echo "the var is:".$arg."<br>";
}
when you add_action, you need to define the $arg value:
add_action('admin_menu', 'my_function', 10, 'my value');
Did you tried to put your function before add_action ?
Use an anonymous function like this:
function my_function($arg) {
echo "the var is: $arg<br>";
}
$arg = "HELP ME";
add_action('admin_menu', function() { global $arg; my_function($arg); }, 10);
See this answer for details.
Related
I would like to use a php variable to input the value as the shortcode name for wordpress.
Basically I have an option where people can create an options and give it a shortcode name.
Something like the following:
Is this possible?
$shortcode_name = "name_here";
function $shortcode_name ($atts) {
// code here
}
add_shortcode ($shortcode_name , $shortcode_name);
Thanks
In PHP 5.3+ you have closures.
$shortcode_name = 'awesome';
${"{$shortcode_name}_fn"} = function($atts) {
print('Awesome shortcode');
};
add_shortcode($shortcode_name, ${"{$shortcode_name}_fn"});
You can also have variable variable names, in this case, the variable that contains the function is named: awesome_fn.
In my blank.php it currently has following:
<?php
// Blank file...
I am using this file to replace a particular template in my WordPress like so:
add_filter( 'comments_template', blank_file' );
function blank_file() {
return PLUGIN_PATH . '/blank.php';
}
However, instead of creating a blank file to return, is it possible to just return a blank value to get the same results? I tried the following which would make sense to me logically, but it didn't work:
function blank_file() {
$blank = '<?php';
return $blank;
}
It's because the function blank_file is supposed to return a path to a blank file.
Try
return '/dev/null';
and
return 'data:text/plain,';
The second will work on not only unix if whatever uses your function supports data URI.
I found a similar question on WordPress Stack Exchange here. However, it looks like the solutions require more coding than what I am currently using which works for me:
add_filter( 'comments_template', 'comments_template', 20, 1 );
function comments_template() {
return plugin_dir_path( __FILE__ ) . 'blank.php';
}
Where blank.php has:
<?php
// Blank file...
I'm using my own cms from scratch, so, i'm adding useful functions for my system, but i got stuck on this:
A phrase is being loaded from lang file on array, in this case, $lang['sign']['server'] = 'Sign in with your {{servername}} registered account:';, and then, by a function, {{servername}} must be replaced by $config['servername'].
What i have so far on my functions class is the following:
public function replaceTags($text)
{
global $config;
return preg_replace("/{{(.*?)}}/" , $config[strtolower("$1")], $text) ;
}
Im calling this function here: $main->set('ssocial', $FUNC->replaceTags($lang['sign']['social']));, but the result is Sign in with your registered account: instead of Sign in with your "Server Name Goes Here" registered account.
Any ideas about why the preg_replace is not retrieving the value?
Also, when $config[”$1”] is inside '' like this '$config[”$1”]', the output is Sign in with your $config[”servername”] registered account:, so i have no clues about what's wrong.
Thanks in advance.
This is a quick and dirty working example using preg_replace_callback
<?php
$config = array('server' => 'my custom text');
function handler($matches){
global $config;
return $config[$matches[1]];
}
function replaceTags($text)
{
return preg_replace_callback("/{{(.*?)}}/" , 'handler', $text) ;
}
print replaceTags("Hello {{server}}");
Output:
Hello my custom text
As for why your code doesn't work: the second parameter of preg_replace is $config[strtolower("$1")], so php will literally look for key "$1" in $config, which probably doesn't exist.
I have a multi-page form.
I would like to execute some custom JavaScript on the last page of this form. Theoretically, all I have to do is retrieve the current page number and write a conditional.
Simple, right? Apparently not.
My original workaround was like this:
if ($('gform_page').last().css('display') !== 'none') {
// perform custom scripts now that the last
// Gravity Form page is being shown
}
but $('...').css('display') returns undefined on every element I've tried this on within the form. Custom scripts were being fired every time the user hit the "Next" button. No cigar.
Then, after reviewing the Gravity Forms documentation, I found two useful-looking events: gform_post_render and gform_page_loaded.
However, the documentation gives no instruction on how to access the parameters.
jQuery(document).bind('gform_page_loaded', function(event, form_id, current_page){
console.log(current_page);
// returns nothing when loaded in the footer
// returns [Object, object] when placed in an HTML field in the form
});
In addition to not having the correct code, I also suspect I don't have the code in the correct place as I have also fruitlessly tried the following in functions.php and in header.php (as the documentation suggests):
<?php
function enqueue_custom_script($form, $is_ajax){
if ($is_ajax) :
echo '<script>console.log(current_page);</script>';
endif;
}
add_action("gform_enqueue_scripts", "enqueue_custom_script", 10, 2);
?>
Question:
What code do I need to retrieve the current page number, and more importantly, where do I place that code?
I got it.
The function rgpost is, apparently, crucial in accessing the current page number. After some muddling around on my own, I was able to get the following code working in both functions.php and just before the wp_head() function in header.php.
function run_script_on_last_page($form) {
if (!is_admin()) {
$current_page = rgpost('gform_source_page_number_' . $form['id']) ? rgpost('gform_source_page_number_' . $form['id']) : 1;
if ($current_page == 10) {
wp_enqueue_script('custom_script', get_template_directory_uri() . '/js/custom_script.js', array('jquery'), null, true);
}
}
}
add_action('gform_enqueue_scripts_63', 'run_script_on_last_page');
If you're copy/pasting the code above, make sure to:
replace 10 with the page you want to check
ensure your parameters are correct in wp_enqueue_script
replace 63 with your form ID
Some resources I found useful:
this section of the documentation for the gform_validation filter
the documentation for gform_enqueue_scripts.
The OPs accepted answer might well work but it doesn't work if you have the form setup to paginate using Ajax.
In that case I could only get it working using Javascript and the following method;
http://www.gravityhelp.com/documentation/page/Gform_post_render
jQuery(document).bind('gform_post_render', function (event, formId, current_page) {
if (current_page == 2) {
// do something
}
});
You could of course use the formId parameter to limit this to a specific form
The currently accepted answer only works if the user never goes to a previous page in the form, if they do, then gform_sourge_page_number always lags by one. I found a better solution (using this hook for an example, but you should be able to use it within any hook that has the $form passed to it):
function run_script_on_last_page( $form) {
if ( !is_admin() ) {
if ( \GFFormDisplay::get_current_page( $form['id'] ) == 10) {
wp_enqueue_script( 'custom_script', get_template_directory_uri() . '/js/custom_script.js', array( 'jquery' ), null, true );
}
}
}
add_action( 'gform_enqueue_scripts_63', 'run_script_on_last_page' );
GFFormDisplay::get_current_page( $form_id ) is one of many handy undocumented functions.
I wrote a little function that returns the current page:
// Get Gravity Forms Current Page
// Syntax: gf_current_page()
function gf_get_current_page()
{
return rgpost('gform_source_page_number_' . $_POST['gform_submit']) ? rgpost('gform_target_page_number_' . $_POST['gform_submit']) : 1;
}
Further to the accepted answer, here is an example of finding the current page, and dynamically finding how many pages are in the form. This example changes button text based on whether it is the last page of the form, instead of enqueueing a script.
// Change the text of the 'Next' form button to 'Submit' when
// the current page is the final page of the form
add_filter( 'gform_next_button', 'next_to_submit', 10, 2 );
function next_to_submit( $next_button, $form ) {
$replacement_next_button = $next_button;
$last_page_number = 1;
foreach ($form['fields'] as $field) {
$is_hidden = RGFormsModel::is_field_hidden( $form, $field, array() );
if ($field['pageNumber'] > $last_page_number && !$is_hidden) {
$last_page_number = $field['pageNumber'];
}
}
$current_page_number = rgpost('gform_source_page_number_' . $form['id']) ? rgpost('gform_source_page_number_' . $form['id']) : 1;
if ($last_page_number === $current_page_number) {
// If the current page is the final page
$replacement_next_button = str_replace( 'Next', 'Submit', $next_button );
}
return $replacement_next_button;
}
Following code works for me in JavaScript:
$('.gf_step_active .gf_step_number').html()
It will give you the page number of the current page in multi-page form.
Using Jquery
var current_page_ = 1+parseInt(jQuery('.gform_page:visible').index());
Try using this one:
var current_visible_page = jQuery('.gf_step_active .gf_step_number').html();
console.log(current_visible_page);
Use the above method in the console to check how it's working.
Can I basically do something like:
register_function_hook('myFunctionHook');
so then when any function is run:
functionA(); //The hook runs myFunctionHook();
anoterFunction(); //The hook runs myFunctionHook();
Class::functionA(); //The hook runs myFunctionHook();
Does such a thing exist?
-- Edit --
What I want to do is to get a breakdown of durations of each function. Ie. Performance Tuning. I want to get an idea of what takes all the time without installing xDebug on my Apache server, however I don't know if it is possible.
It's possible with register_tick_function(), also check this comment on the PHP manual:
$script_stats = array();
$time = microtime(true);
function track_stats(){
global $script_stats,$time;
$trace = debug_backtrace();
$exe_time = (microtime(true) - $time) * 1000;
$func_args = implode(", ",$trace[1]["args"]);
$script_stats[] = array(
"current_time" => microtime(true),
"memory" => memory_get_usage(true),
"file" => $trace[1]["file"].': '.$trace[1]["line"],
"function" => $trace[1]["function"].'('.$func_args.')',
"called_by" => $trace[2]["function"].' in '.$trace[2]["file"].': '.$trace[2]["line"],
"ns" => $exe_time
);
$time = microtime(true);
}
declare(ticks = 1);
register_tick_function("track_stats");
// the rest of your project code
// output $script_stats into a html table or something
This "hooks" to everything, not just functions but I think it fits your purpose.
No, its not possible the way you like
But You can achieve something close with inheritance.
class Vehicle {
function __construct() {
$this->hookFunction();
}
function hookFunction() {
//
}
}
class Car extends Vehicle {
}
Class Toyota extends Car {
}
new Toyota(); // will you hook function
// this exclude static call to member functions, or other inline functions.
What you looking for is called profiler. And PQP looks like one, which is standalone.
Instead of polluting the code, you should use a real Profiler, like that one provided by xdebug
Not sure if the Topic Starter needs this anymore, but perhaps others can still benefit from this.
There is a PHP lib, written completely in PHP, that allows you to do exactly what you want.
Here's an article about how it works, including the source code:
http://phpmyweb.net/2012/04/26/write-an-awesome-plugin-system-in-php/
It allows you to register a function from a class to be hooked. So it basically executes your code first, and then you determine wether you want to call the original function too after your code has been executed.