Wordpress Shortcode not passing variable from function (Newbie) - php

Here is the snippet of code in question:
function hoursearned_func($user) {
$key = 'Service Hours Earned';
if(isset($user[$key])) {
$result = $user[$key];
}
return "Service Hours Earned: ".$result." Hours";
}
add_shortcode('hoursearned', 'hoursearned_func');
This small function simply returns the value of an array given the key, but when calling the shortcode, [hoursearned], it only displays:
Service Hours Earned: Hours
rather than:
Service Hours Earned: 200 Hours
Where 200 is a string that is returned by the function hoursearned_func given $user.
For some reason Wordpress is not passing the returned variables from the functions to the shortcodes. How can I get Wordpress to show the result from the function?
Here is the full code if that helps... (note that all of this is being loaded as a plugin)
//Dump CSV file (SalesForce Report) to php array to be parsed..
add_action('dump_csv_array', 'dump_csv_array', 10);
function dump_csv_array(){
$data = array();
$header = NULL;
if (($file = fopen('http://blah.com/info.csv', 'r')) !==FALSE) { //The link to the CSV is insignificant
while (($row = fgetcsv($file, 1000, ",")) !==FALSE) {
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($file);
}
return $data;
}
$multiarray = (array) dump_csv_array();
global $current_user;
get_currentuserinfo();
$user_email = $current_user->user_email;
//Parses the multidimensional array of Dumped CSV info. Looks up the current user's email and returns a single array of the current user's SalesForce information.
function parse_array($multiarray, $user_email){
$array = (array) $multiarray;
$email = $user_email;
if(is_user_logged_in() === true ) {
foreach($array as $subarray) {
if(isset($subarray['Email']) && $subarray['Email'] == $email) {
$data = $subarray;
}
}
}
else {
return NULL;
}
return $data;
}
$user = parse_array($multiarray, $user_email);
//Defines Shortcodes and their Functions
function hoursearned_func($user) {
$key = 'Service Hours Earned';
if(isset($user[$key])) {
$result = $user[$key];
}
return "Service Hours Earned: ".$result." Hours";
}
function hoursawarded_func($user) {
$key = 'Service Hours Awarded';
if(isset($user[$key])) {
$result = $user[$key];
}
return "Service Hours Awarded: ".$result." Hours";
}
function rank_func($user) {
$key = 'Rank';
if(isset($user[$key])) {
$result = $user[$key];
}
return "Rank: ".$result;
}
function memstatus_func($user) {
$key = 'Membership Status';
if(isset($user[$key])) {
$result = $user[$key];
}
return "Status: ".$result;
}
function register($atts) {
add_shortcode( 'hoursearned', 'hoursearned_func');
add_shortcode( 'hoursawarded', 'servicehours_func');
add_shortcode( 'rank', 'rank_func');
add_shortcode( 'memstatus', 'memstatus_func');
}
add_action('init', 'register');
var_dump(hoursearned_func($user));

Try to create a shortcode with attributes, (or) retrieve the $user data inside the shortcode's function and set them as default values.
function example_func($atts) {
$user = get_user_array(); //Retrieve the data
$atts = shortcode_atts($user, $atts);
return 'example: ' . $atts['foo'] . ' ' . $atts['bar'];
}
add_shortcode('example', 'example_func');
Have a look at the Shortcode API it basically explains everything.

Related

Is it possible to update inventory_policy for all products using API in Shopify?

From my PHP application, I want to update the inventory_policy (continue/deny) of all products using API. Is there any way to do so without a loop?
I did not find any way to update it at once. Hence, I have updated it one by one. Please have the code below.
public function update_inventory_policy_for_all_item($inventory_policy, $page_info=null){
$response = $this->do_get("/admin/api/2021-04/products.json?limit=250".$page_info);
if ($response === FALSE)
{
return false;
}
$result_products = $response['body']['products'];
$headers = $response['headers'];
foreach($result_products as $shopify_product){
foreach($shopify_product['variants'] as $variant){
$variant_id = $variant['id'];
$data['variant'] = array(
'id' => $variant['id'],
'inventory_policy' => $inventory_policy,
);
$this->do_put("/admin/api/2021-04/variants/$variant_id.json", $data);
}
}
if(isset($headers['link'])) {
$links = explode(',', $headers['link']);
foreach($links as $link) {
$next_page = false;
if(strpos($link, 'rel="next"')) {
$next_page = $link;
}
}
if($next_page) {
preg_match('~<(.*?)>~', $next_page, $next);
$url_components = parse_url($next[1]);
parse_str($url_components['query'], $params);
$page_info = '&page_info=' . $params['page_info'];
$this->update_inventory_policy_for_all_item($inventory_policy, $page_info);
}
}
return true;
}

PHP get link from txtfile, unset this link inside the array and get random array value

I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}

Get only a specified name of email

I have a problem with preg_math. So I have this methode :
public function filterUsers($a_users){
$a_authorizedEmail = array(
'#test.com',
'#test1.com'
);
$a_response = array();
foreach ($a_users as $user) {
if(false !== $email_user = EmailRepository::getEmail($user['id'])){
foreach($a_authorizedEmail as $email){
echo $email_user;
if(preg_match($email, $email_user)){
$a_response[]= $user;
}
}
}
}
return $a_response;
}
The array with $a_users : I have a user with email hcost#test.com. But in the return the array is empty. Probably I doen't made a correct verification. Please help me
Do this:
public function filterUsers($a_users){
$a_authorizedEmail = array(
'#test.com',
'#test1.com'
);
$pattern = "/".implode("|",$a_authorizedEmail)."$/"; //Note the "/" start and end delimiter as well as the $ that indicates end of line
$a_response = array();
foreach ($a_users as $user) {
$email_user = EmailRepository::getEmail($user['id']);
if(false !== $email_user){
echo $email_user;
if(preg_match($pattern, $email_user)){
$a_response[]= $user;
}
}
}
return $a_response;
}

php Notice: array to string conversion

hi all im new ish to php and new to stack overflow but do have some knowledge in php what im trying to do is get one value from my returned array call from an api function is
$character->getSlot('head');
using print_r gives me:
Array (
[icon] => http://url to image location
[name] => Wizard's Petasos
[slot] => head )
if i echo $character->getSlot('head', 'name); gives me C:\xampp\htdocs\test\index.php on line 19 and just returns the word Array
here is the section of index.php
<?php
include('api.php');
// Call API
$API = new LodestoneAPI();
// Search for: Demonic Pagan on Sargatanas
$character = $API->get(array(
"name" => "Darka Munday",
"server" => "Ragnarok"
));
// Basic character data
echo "Character ID: " . $character->getID();
$ID = $character->getID();
$API->parseProfile($ID);
$Character = $API->getCharacterByID($ID);
echo $character->getSlot('head', 'name');
and the section of the api just in case
// GEAR
public function setGear($Array)
{
$this->Gear['slots'] = count($Array);
$GearArray = NULL;
// Loop through gear equipped
$Main = NULL;
foreach($Array as $A)
{
// Temp array
$Temp = array();
// Loop through data
$i = 0;
foreach($A as $Line)
{
// Item Icon
if (stripos($Line, 'socket_64') !== false) { $Data = trim(explode('"', $A[$i + 1])[1]); $Temp['icon'] = $Data; }
if (stripos($Line, 'item_name') !== false) { $Data = trim(str_ireplace(array('>', '"'), NULL, strip_tags(html_entity_decode($A[$i + 2])))); $Temp['name'] = htmlspecialchars_decode(trim($Data), ENT_QUOTES); }
if (stripos($Line, 'item_name') !== false) {
$Data = htmlspecialchars_decode(trim(html_entity_decode($A[$i + 3])), ENT_QUOTES);
if (
strpos($Data, " Arm") !== false ||
strpos($Data, " Grimoire") !== false ||
strpos($Data, " Tool") !== false
)
{ $Main = $Data; $Data = 'Main'; }
$Temp['slot'] = strtolower($Data);
}
// Increment
$i++;
}
// Slot manipulation
$Slot = $Temp['slot'];
if (isset($GearArray[$Slot])) { $Slot = $Slot . 2; }
// Append array
$GearArray['numbers'][] = $Temp;
$GearArray['slots'][$Slot] = $Temp;
}
// Set Gear
$this->Gear['equipped'] = $GearArray;
// Set Active Class
$classjob = str_ireplace('Two-Handed ', NULL, explode("'", $Main)[0]);
$this->Stats['active']['class'] = $classjob;
if (isset($this->Gear['soul crystal'])) { $this->Stats['active']['job'] = str_ireplace("Soul of the ", NULL, $this->Gear['soul crystal']['name']); }
}
public function getGear() { return $this->Gear; }
public function getEquipped($Type) { return $this->Gear['equipped'][$Type]; }
public function getSlot($Slot) { return $this->Gear['equipped']['slots'][$Slot]; }
the solution to this is probably really simple and im being really dumb but any help would be great :) thanks in advance
public function getSlot($Slot) {
return $this->Gear['equipped']['slots'][$Slot];
}
getSlot method have only one argument. You are passing another argument but getSlot method returns array.
You can do like this :
public function getSlot($Slot, $param = null) {
if(empty($param)) {
return $this->Gear['equipped']['slots'][$Slot];
} else {
if(isset($this->Gear['equipped']['slots'][$Slot][$param] )) {
return $this->Gear['equipped']['slots'][$Slot][$param];
} else {
return null;
}
}
}
OR
echo $character->getSlot('head')['name'] // If version is >= 5.4.*
If version < 5.4.*
$slot = $character->getSlot('head');
echo $slot['name'];

Return in foreach showing only 1st value

I have problem. In my function, return shows only first player from server. I wanted to show all players from server, but i cant get this working. Here is my code:
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
return '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
}
}
}
You're returning from within your loop.
Instead, you should concatenate the results for each iteration and then return that concatenated string outside the loop.
e.g.
$result = "";
foreach($aPlayers as $sValue) {
# add to $result...
}
return $result
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
$ret = '';
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
$ret .= '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
return $ret;
}
}
}
In a function you can only return ONE value.
Try creating a list of players and return the list when all records have been added to it.
In your case, list of players will result in an array of players

Categories