Use a variable as a function name in PHP - php

I'm creating a dynamic function in WordPress that requires I create my function names dynamically.
In this instance, I need to generate a unique function name for this gravityforms code:
add_filter( 'gform_validation_message', 'change_message', 10, 2 );
function change_message( $message, $form ) {
return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
}
So, I have a variable (which will change from time to time) that I want to use for my function name...
$newitem = 'new_item';
...and tried this...
add_filter( 'gform_validation_message', $newitem, 10, 2 );
function $newitem( $message, $form ) {
return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
}
...but obviously that does not work. But I think you get the idea of what I am trying to achieve.
Is anything like this even possible?
Any help is appreciated.

$thing = 'some_function';
$$thing = function() {
echo 'hi';
};
$some_function();
Source - Use a variable to define a PHP function

You can simply pass Anonymous function to add_filter function as parameter:
$newitem = function($message, $form) {
return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
};
add_filter('gform_validation_message', $newitem, 10, 2);

Related

Wordpress: nav_menu_link_attributes won't accept variable as attribute

I am trying to take a custom color that was chosen by the user in the Customizer, and add it as an html attribute to the links that are outputted by a specific menu.
Here is my code so far:
// Gets the footer link color, if assigned by user.
if (get_theme_mod('theme_footer_link_color')) {
$footerLinkColorAttribute = 'color:' . get_theme_mod('theme_footer_link_color', 'default_value') . ';';
}
function add_customizer_link_color_attribute_to_footer_menu_links($atts, $item, $args){
if ($args->theme_location == 'footerNavLocation') {
$atts['style'] = $footerLinkColorAttribute;
}
return $atts;
}
add_filter('nav_menu_link_attributes', 'add_customizer_link_color_attribute_to_footer_menu_links', 10, 3);
My problem is that the style attribute is taking $footerLinkColorAttribute as plain text, instead of a variable that contains the text set by the user.
How can I get it to be taken as a variable?
I figured it out. I was defining the variable outside of the function, but needed to define it inside of the function:
function add_customizer_link_color_attribute_to_footer_menu_links($atts, $item, $args){
if ($args->theme_location == 'footerNavLocation') {
// If there is a footer link color assigned in the Customizer, this gets it ready to be inserted as an attribute into the link menu link text.
if (get_theme_mod('lets_get_started_footer_link_color')) {
$footerLinkColorAttribute = 'color:' . get_theme_mod('lets_get_started_footer_link_color', 'default_value') . ';';
}
$atts['style'] = $footerLinkColorAttribute;
}
return $atts;
}
add_filter('nav_menu_link_attributes', 'add_customizer_link_color_attribute_to_footer_menu_links', 10, 3);

How can I re-use my wordpress action hook functions as 'normal' functions

I have an function action hook which collects subscriptions from our database. I want to use this so that I can display the subscriptions on the page, but I also want to use this function in another function that calculates the new subscription price. Is this possible?
My code looks somewhat like this
add_action( 'wp_ajax_get_get_subs_with_type', 'get_subs_with_type' );
add_action( 'wp_ajax_nopriv_get_get_subs_with_type', 'get_subs_with_type' );
function get_subs_with_type($sub_type) {
$subs = //get alot of info from database......
echo $subs;
}
But I also want to use this function with a return statement instead of echo to be used in another function.
functon calc_subs(){
$subs = get_subs_with_type();
return $subs[1]->price + 1;
}
So can I use a function tied to an action hook as a 'normal' function as well? Or what should I do?
EDIT:
If there is no good way of doing this, I made a little hacky solution:
add_action( 'wp_ajax_get_get_subs_with_type', 'get_subs_with_type' );
add_action( 'wp_ajax_nopriv_get_get_subs_with_type', 'get_subs_with_type' );
function get_subs_with_type($sub_type) {
$subs = get_sub_from_db()
echo $subs;
}
function get_sub_from_db() {
$subs = //get alot of info from database......
return $subs;
}
Now I can use get_sub_from_db() in my other function as well.
functon calc_subs(){
$subs = get_sub_from_db();
return $subs[1]->price + 1;
}
What do you think of this?
You can for example do something like:
/**
* Returns bla bla bla
* #return array
*/
function get_subs_with_type($sub_type) {
$subs = //get alot of info from database......
return $subs;
}
add_action( 'wp_ajax_get_get_subs_with_type', function () {
echo get_subs_with_type();
});
but remember that while using anonymous function you will not be able to remove this action with remove_action.
The solution you proposed, by creating two different function, one returning the database call & the other calling the first one looks quite good.
Don't forget to add a wp_die(); function after you echoed all this information to the ajax handler. This is required to terminate any ajax call immediately and return a proper response.

Change title tag with filter wpseo_title

I am trying to change the title tag adding a variable (product-brand), but the variable does not show up.
add_filter('wpseo_title', 'filter_product_wpseo_title');
function filter_product_wpseo_title() {
return 'hello'. $_GET[$mysite_slugs['product-brand']] .'hello';
};
}
Also tried this but no luck
add_filter('wpseo_title', 'filter_product_wpseo_title');
function filter_product_wpseo_title() {
$productbrand = $_GET[$mysite_slugs['product-brand']];
return 'hello'. $productbrand .'hello';
};
}
I'm assuming your URL has the parameter .com/?product-brand=foo. Make sure you have added the priority to your filter. This should do the trick!
add_filter('wpseo_title', 'filter_product_wpseo_title', 10, 1);
function filter_product_wpseo_title($title) {
$title = 'hello '. $_GET['product-brand'] .' hello';
return $title;
}

function parameter as a part of variable name

I was wondering if I can pass function argument as a part of variables name and create new one. Like example below
function do_anything($name) {
global ${$name}_anything;
${$name}_anything = 'hello_world';
}
do_anything('unique');
echo $unique_anything;
Don't tell anyone I wrote this.
<?php
function do_anything($name) {
global ${$name . "_anything"};
${$name . "_anything"} = 'hello_world';
}
do_anything('unique');
echo $unique_anything;

PHP class doesn't echo another php page at the appropriate place

Alright, I'm using a page creating class I found as below but when I want to use a php page -that again includes and uses a class file- for the content it either echoes on the top or the bottom of the page... I even tried to make the page a function() and call it at the $Content string but no use, again it echoed on the top of the page... How can i use a php page as a content in this class, or what should i change to use a php file?
Please keep in mind that I'm new to classes so feel free to assume some beginner mistakes.
<?php
class Page {
var $Title;
var $Keywords;
var $Content;
function Display( ) {
echo "<HTML>\n<HEAD>\n";
$this->DisplayTitle( );
$this->DisplayKeywords( );
echo "\n</HEAD>\n<BODY>\n";
echo $this->Content;
echo "\n</BODY>\n</HTML>\n";
}
function DisplayTitle( ) {
echo "<TITLE>" . $this->Title . "</TITLE>\n";
}
function DisplayKeywords( ) {
echo '<META NAME="keywords" CONTENT="' . $this->Keywords . '">';
}
function SetContent( $Data ) {
$this->Content = $Data;
}
}
?>
Usage:
<?php
include "page.class";
$Sample = new Page;
$Content = "<P>I want my php file's contents here.</P>";
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent( $Content );
$Sample->Display( );
?>
What if I wanted to make the content something like $Content = " < ? echo 'test'; ? >"; I know this isn't valid but what i'm trying to do is something like that or something like $Content = " output of the whateversinhere.php ";. how should I object orient another page therefore getting its contents into a string here?
You should NOT echo anything inside your class, instead the class should have a method getMarkup(), which will return a string containing the whole markup. Then you can echo that string in your view.
Additional tipps:
variables and method names start with a small letter!
title and keywords should have getters and setters too
make your variables private (private $title, etc.)
let me clean this up for you, you will notice some changes:
class Page
{
private $title = 'No Title';
private $keywords = array();
private $content = '';
public function setTitle($title)
{
$this->title = (string)$title;
}
public function addKeywords($keywords)
{
$this->keywords = array_merge($this->keywords, (func_num_args() > 1) ? func_get_args() : (array)$keywords;
}
function setContent($content)
{
$this->content = $content;
}
function appendContent($content)
{
$this->content .= $content;
}
function prependContent($content)
{
$this->content = $content . $this->content;;
}
private function display()
{
/*
* Display output here
*/
echo $this->title;
echo implode(',',str_replace(',','',$this->title));
echo $this->contents;
}
}
pretty simple usage:
$Page = new Page;
$Page->setTitle("Hello World");
$page->addKeywords("keyword1","keyword2","keyword3","keyword4");
//Content
$this->setContent("World");
$this->prependContent("Hello");
$this->appendContent(".");
//Display
$this->display();
Just got to fill in the blanks, you will learn as time goes on that you should not be using html directly within your class, and that you would split the above into several class such as Head,Body,Footer,Doctype and have a page class that brings them all together.
Use Output Control Functions.
<?php
include "page.class";
$Sample = new Page;
ob_start();
include "foobar.php";//What you want to include.
$content = ob_get_contents();
ob_end_clean();
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent($content);
$Sample->Display( );
?>

Categories