PHP: Alternative to returning a blank file - php

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...

Related

Wordpress PHP - How to update plugin setting value in main file

This is from inside my Wordpress plugin, inside the main file:
function my_plugin_install() {
$my_site_url = get_site_url();
$my_options['my_site_url'] = $my_site_url;
// Save
}
register_activation_hook(__FILE__, 'my_plugin_install');
Currently, the install is successful but the 'my_site_url' option is not saved. I'm assuming because the way I'm using the $my_options array at this point doesn't mean anything. It should save this data to the wp_options table.
I can't seem to get this to save, or even find a way to test this as using "echo" gives Wordpress an error during install. Is there a best method for running a script and updating the database during install?
Thanks in advance.
You need to use the WordPress function update_option to save your option value:
function my_plugin_install() {
$my_site_url = get_site_url();
update_option('my_site_url', $my_site_url);
}
register_activation_hook(__FILE__, 'my_plugin_install');
And then later, when you need that value, you can use get_option:
$my_site_url = get_option('my_site_url');
*UPDATE
Since it appears you want to manage multiple of your own options, then I suggest using a simple "utility" function, like so:
function update_my_option($key, $value) {
// Load all of the option values from wp_options
$all_options = get_option('my_options');
// Update just the one option you passed in
$all_options[$key] = $value;
// Save to wp_options
update_option('my_options');
}
And, an appropriate getter function:
function get_my_option($key, $default = NULL) {
// Load all of your options from wp_options
$all_options = get_option('my_options');
// Return just the one option you are asking for
return (isset($all_options[$key])) ? $all_options[$key] : $default;
}
Then, rather than calling update_option directly, you'll call this function, as illustrated below:
function my_plugin_install() {
$my_site_url = get_site_url();
update_my_option('my_site_url', $my_site_url);
}
And, to get one of your options:
$my_site_url = get_my_option('my_site_url');

preg_replace not retrieving correct data

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.

Allowing users to make template- Scan code for functions

I am currently creating a web app and I would like to allow my users to create a template. I would only allow them to use HTML and some functions to get some values, so I have some functions like
getDescription(); but since its PHP I also have other function (e.g. phpinfo();) which I don't want them to use.
Is it possible to set a filter (like in_array) to check if functions other than declared are used?
Or is there an Template engine or something else which does that.
I am very new to templating and I couldn't find anything.
If they are only creating HTML templates, you could allow them to put for example;
<div>
[PHP]getDescriptions()[PHP]
</div>
<div>
[PHP]phpinfo()[/PHP]
</div>
Then in your parsing file when they save or whatever, you could have
$allowedFunctions = array('getDescriptions');
$input = '';//html from the template
foreach($allowedFunctions as $key => $value){
$myVal = $value();
$input = str_replace('[PHP]'.$value.'()[/PHP]',$myVal,$input);
}
This would replace [PHP]getDescriptions()[/PHP] with whatever is returned from getDescriptions()...
and phpinfo() wouldnt change.
you can check if a function exists with function_exists. If you want them to use the functions you defined for that purpose only you could prefix those function with something like 'tpl_*". like this:
function tpl_getDescription() {/*code here*/}
and then when you user tries to implement a function like getDescription you add "tpl_" to it and check if that function exists with function_exists().
if(function_exists('tpl_' . $userFuncName))
{
call_user_func('tpl_' . $userFuncName)
}
that way even if the user tries to evoke a native php function tpl_ will be prefixed and if will return false.
Yes, you could easily make a script that enumerates all user functions in an external file. Lets say you have this "template", template.php :
<?
function getDescription() {
}
function userFunc() {
}
function anotherFunction() {
}
?>
then you could get a list of all functions in template.php this way :
<?
include('template.php');
$functions = get_defined_functions();
echo '<pre>';
print_r($functions['user']);
echo '</pre>';
?>
would output :
Array
(
[0] => getdescription
[1] => userfunc
[2] => anotherfunction
)
I would call this script through AJAX, like getfunctions.php?file=template.php which returned a JSON with all user functions inside template.php.

Gravity Forms - Get Current Page Number

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.

passing argument using add_action in wordpress!

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.

Categories