Autogenerate wordpress shortcodes using array? - php

I was create a shortcode which automatically generate shortcodes with given array key and value. Function names does not generate dynamically.
Note: Array KEY = ShortcodeName and Value = Wordpress Option field.
add_shortcode("auto_gen", "auto_gen");
function auto_gen() {
$a = array(
"get_address" => "mg_admin_address",
"get_phone" => "mg_admin_phone",
"get_fax" => "mg_admin_fax",
"get_email" => "mg_admin_email",
"get_hrs_mon" => "mg_work_hrs_mon_frd",
"get_hrs_sat" => "mg_work_hrs_sat"
);
foreach ($a as $k => $v) {
if(has_shortcode($k)) {
echo "<br>Found: ". $k;
} else {
add_shortcode($k, $k. "_init");
function $k. "_init"() {
return get_option[$v, ''];
}
}
add_shortcode();
echo $k ." -> ". $v. "<br />";
}
}
There is any possible way to do this.
NOTE:
Here, get_address array key is a shortcode. And it is dynamically generate when It pass though loop. get_address is changable. If I change get_address with get_user_address then get_user_address generate generated. "get_address", "get_phone" are CHANGABLE at END LEVEL.
Developer also generate shortcodes to access created wp_options useing get_options, simply pushing elements in array. e.g. "shortcode_name" => "option_name"

The function add_shortcode has a third parameter that contains the current shortcode, so the same callback can be used multiple times:
$all = array( 'address', 'phone', 'fax', 'email', 'hrs_mon', 'hrs_sat' );
foreach ( $all as $s )
add_shortcode( "get_$s", 'general_shortcode' );
function general_shortcode( $atts, $content = '', $shortcode = '' )
{
switch( $shortcode )
{
case 'get_address':
$return = 'ADDRESS';
break;
case 'get_phone':
$return = 'PHONE';
break;
default:
$return = 'OTHER SHORTCODES';
break;
}
return $return;
}
Another possibility:
Class AllShortcodes{
private $all = array(
"get_address" => "mg_admin_address",
"get_phone" => "mg_admin_phone",
"get_fax" => "mg_admin_fax",
"get_email" => "mg_admin_email",
"get_hrs_mon" => "mg_work_hrs_mon_frd",
"get_hrs_sat" => "mg_work_hrs_sat"
);
public function __construct() {
foreach ( $this->all as $key => $value )
add_shortcode( $key, array( $this, 'general_shortcode' ) );
}
public function general_shortcode( $atts, $content = '', $shortcode = '' )
{
return $this->all[$shortcode];
}
}
$myShortcodes = new AllShortcodes;

Try following code:
add_shortcode("auto_gen", "auto_gen");
function auto_gen() {
$a = array(
"get_address" => "mg_admin_address",
"get_phone" => "mg_admin_phone",
"get_fax" => "mg_admin_fax",
"get_email" => "mg_admin_email",
"get_hrs_mon" => "mg_work_hrs_mon_frd",
"get_hrs_sat" => "mg_work_hrs_sat"
);
foreach ($a as $k => $v) {
if(has_shortcode($v,$k)) {
echo "<br>Found: ". $k;
} else {
add_shortcode($k, $k."_init");
$func =$k."_init";
$func($v);
}
echo $k ." -> ". $v. "<br />";
}
}
function get_address_init ($v) {
return get_option($v, '');
}
function get_phone_init ($v) {
return get_option($v, '');
}
function get_fax_init ($v) {
return get_option($v, '');
}
function get_email_init ($v) {
return get_option($v, '');
}
function get_hrs_mon_init ($v) {
return get_option($v, '');
}
function get_hrs_sat_init ($v) {
return get_option($v, '');
}

Related

Function inside the same function PHP

I'm busy with cleaning a WordPress parse_blocks() array.
Array:
Parse blocks
blockName
attrs
innerBlocks (0)
InnerBlocks (0)
blockName
attrs
innerBlocks (1)
InnerBlocks (1)
blockName
attrs
innerBlocks (2)
What I want is making a function which repeats each innerblock.
As you see above the array Parse block has innerblocks and those can get also innerblocks (2 times).
I made a simple function cleanBlock($block)
function cleanBlock($block)
{
if (isset($block['blockName']) && $block['blockName'] != '') {
$splitType = explode('/', $block['blockName']);
$innerBlocks = $block['innerBlocks'];
$block = array(
'type' => $splitType[1],
'attrs' => '',
'innerblocks' => $innerBlocks,
);
return $block;
}
}
There you find "innerblock" my idea was to run the cleanBlock($innerBlocks) again, but if I do that it doesn't work because the $block is made before I can get the innerblock, it's hard to explain I hope you know what I mean.
This is what I want, but this code doesn't work at all:
function cleanBlock($block)
{
if (isset($block['blockName']) && $block['blockName'] != '') {
$splitType = explode('/', $block['blockName']);
$block = array(
'type' => $splitType[1],
'attrs' => '',
'innerblocks' => cleanBlock($block['innerBlocks']),
);
return $block;
}
}
After the function I make the final array:
$newPDFarray = [];
foreach ($parseBlocks as $key => $group) {
$block = cleanBlock($group);
$newPDFarray[] = $block;
}
Don't know if this is the right or short solution but for me it works:
function cleanBlock($block)
{
if (isset($block['blockName']) && $block['blockName'] != '') {
$splitType = explode('/', $block['blockName']);
$innerBlocks = [];
foreach ($block['innerBlocks'] as $block) {
$innerBlocks[] = cleanBlock($block);
}
$block = array(
'type' => $splitType[1],
'attrs' => $block['attrs'],
'innerBlocks' => $innerBlocks,
);
return $block;
}
}
$newPDFarray = [];
foreach ($parseBlocks as $key => $group) {
if ($group['blockName'] != '') {
$questionGroup = cleanBlock($group);
$newPDFarray[] = $questionGroup;
}
}

How to dynamically fill key and value in an associative array using for loop in PHP

$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
Here i added
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4"
using $str Dynamically with the help of for loop because it is dynamic not fixed.
I want to make this array like the below, so it can work and print correct output - It's my desired output(I want this array like this to be working)
array(
"data"=>array(
"userid"=>"$row->uid",
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"acc_id"=>"$acc_id",
"tloop"=>"$timeloopc"
),
"next"=>"$next"
);
Output is -
But array taking the value of $str as string and when i print thisit shows output -
Array (
[data] => Array (
[user1] => 1
[0] => "value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"value5"=>"$row->field5"
[user2] => 2
[fi] => 3
)
[next] => 4
)
The Above output is issue... Here array processing some key and value but not processing $str value... it's taking it as sting.
It's now processing the $str values as string from "value1" and "field1"..to..4
Help me to dynamically fill key and value in an associative array using for loop.
In the array "value1 and field1" - here numbers are dynamic - "value2" and "field2"...
When i am making array dynamic, it's not working like array. If i make it static it works fine.
So please help me to make $str value from string to array value(object)...
Here is complete code -
<?php
$ct = 4;
$str = '';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= '"value';
$cuntc = $cunt.'"';
$rw = '"$row';
$fild= "field";
$cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc;
$str .= $cp . ',';
}
//trim the , from last value
$str = rtrim($str, ",");
$main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4");
print_r($main);
?>
I don't know what exactly you want.
There is a code, which build array you'd like to have:
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$ct = 4;
$subArray = array();
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$resultArray['data'][$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
echo "<pre>";
var_dump($resultArray);
echo "</pre>";
But if you don't need restricted key ordering, you can use something like this (it's rebuild $main array):
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$fields = array();
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$fields[$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
foreach ($fields as $key => $value) {
$main['data'][$key] = $value;
}
And there is solution with functions:
function generateFieldArray($keyName, $obj, $field, $rowCount)
{
$resultArray = array();
for($count=1; $count<=$rowCount; $count++)
{
$resultArray[$keyName . $count] = '$' . $obj . '->' . $field .$count;
}
return $resultArray;
}
function buildMainArray($inputArray, $keyName, $obj, $field, $rowCount)
{
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$inputArray['data'][$key] = $value;
}
return $inputArray;
}
function buildMainArray2($inputArray, $keyName, $obj, $field, $rowCount)
{
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$resultArray['data'][$key] = $value;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
return $resultArray;
}
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$result = buildMainArray($main, 'value', 'row', 'field', 4);
// or
$result = buildMainArray2($main, 'value', 'row', 'field', 4);

Exchange HTML in for AMP Pages

Is there a way to change HTML in AMP Pages? Example:
Make every <span class="example1">...</span> to ...
Or even better, change specific Shortcodes in Wordpress to ...?
I found a solution to switch shortcodes:
// AMP change thrive-shortcode to landingpage link
function add_shortcode_amp($content) {
if (function_exists( 'is_amp_endpoint' ) && is_amp_endpoint()) {
/// Define shortcode-name
$mb_shortc = 'thrive_2step';
/// Define Mappings (thrive_2step id => Target URL for links in AMP)
$ampMappings = array(
"17503" => 'https://www.test.de/schreibtisch-workout-2',
"17505" => 'https://www.test.de/merkmale-arbeitsplatz-kostenlos',
"17506" => 'https://www.test.de/hoehenverstellbarer-schreibtisch-rentenverischerung-antrag');
/// Init Regex arrays
$mb_rexp = array();
$subst = array();
foreach ($ampMappings as $key => $value) {
$mb_rexp[] = '/\[('.$mb_shortc.').*?.id=[\'"]'.$key.'[\'"].*?\](.*?)\[\/\1\]?/';
$subst[] = '${2}';
}
/// Process Content
return preg_replace($mb_rexp, $subst, $content);
}
return $content;
}
add_filter( 'the_content', 'add_shortcode_amp', 6);
function mbtest_hello_world() {
return '<a>Hello World</a>';
}
add_shortcode('AMPTEST', 'mbtest_hello_world');
function shortcode_switch4amp( $atts) {
extract( shortcode_atts( array(
'regular' => 'regular',
'amp' => 'amp'
), $atts ) );
if (function_exists( 'is_amp_endpoint' ) && is_amp_endpoint()) {
return do_shortcode(str_replace(array("{","}"), array("[","]"),$amp));
} else {
return do_shortcode(str_replace(array("{","}"), array("[","]"), $regular));
}
}
add_shortcode('switch4amp', 'shortcode_switch4amp');

Echo a value from an array based on function parameters

I need to be able to echo a value from a private property in one of my classes if a method is called within the class. It's a little tricky to explain so let me demostrate and hopefully someone can fill in the blank for me :)
<?php
class test {
private $array['teachers']['classes'][23] = "John";
public function __construct($required_array) {
$this->array['teachers']['classes'][23] = "John";
$this->array['students'][444] = "Mary";
$this->echo_array($required_array);
}
public function echo_array($array) {
// Echo the value from the private $this->array;
// remembering that the array I pass can have either
// 1 - 1000 possible array values which needs to be
// appended to the search.
}
}
// Getting the teacher:
$test = new test(array('teachers','classes',23));
// Getting the student:
$test = new test(array('students',444));
?>
Is this possible?
$tmp = $this->array;
foreach ($array as $key) {
$tmp = $tmp[$key];
}
// $tmp === 'John'
return $tmp; // never echo values but only return them
An other approach to get value;
class Foo {
private $error = false,
$stack = array(
'teachers' => array(
'classes' => array(
23 => 'John',
24 => 'Jack',
)
)
);
public function getValue() {
$query = func_get_args();
$stack = $this->stack;
$result = null;
foreach ($query as $i) {
if (!isset($stack[$i])) {
$result = null;
break;
}
$stack = $stack[$i];
$result = $stack;
}
if (null !== $result) {
return $result;
}
// Optional
// trigger_error("$teacher -> $class -> $number not found `test` class", E_USER_NOTICE);
// or
$this->error = true;
}
public function isError() {
return $this->error;
}
}
$foo = new Foo();
$val = $foo->getValue('teachers', 'classes', 24); // Jack
// $val = $foo->getValue('teachers', 'classes'); // array: John, Jack
// $val = $foo->getValue('teachers', 'classes', 25); // error
if (!$foo->isError()) {
print_r($val);
} else {
print 'Value not found!';
}

PHP Generate Array from Function Arguments

I have a function that I want to generate an array with. The format of the array is specific and only values need to be changed based on the arguments of my function. Here's the function:
function generatearray($name1, $field1, $name2, $field2) {
$language = ($user->language) ? $user->language : 'und';
$edit = array(
$name1 => array(
$language => array(
0 => array(
'value' => $field1,
),
),
), // ..... other elements $name2
);
return $edit;
}
$name2 and $field2 are optional arguments.
Not sure what the question is...but this code will do exactly what you're wanting to know about...a way to build an array based on up to 2 name/value pairs provided to a function.
printarray(generatearray('name_one','field_one','name_two','field_two'));
function generatearray($name1, $field1, $name2 = null, $field2 = null) {
$new_array = array();
$language = isset($user->language) ? $user->language : 'und';
$new_array[$name1][$language] = $field1;
if (!is_null($name2) && !is_null($field2)) {
$new_array[$name2][$language] = $field2;
}
return $new_array;
}
function printarray($arr) {
foreach ($arr as $user_key => $user_value) {
echo "User: ".$user_key."<br />";
foreach ($user_value as $language_key=>$language_value) {
echo "Language: ".$language_value."<br />";
}
}
}

Categories