I have an array called $array_all;
This array will always have 3 possible values:
1,
1,2,
1,2,3,
I created a string from the array while in a foreach loop and concatenated a comma at the end.
So, now I have a nice string that outputs the exact value the way it should.
1,2,3, I can copy this output from my browser and insert it into my wordpress function and everything displays perfectly.
The problem arises when I insert this string variable in the wordpress function directly, it fails.
Anybody have any ideas?
Code below:
<?php
$faux_array = array();
$faux_array_all;
if($five_loans != ''):
$faux_array[] = "781";
endif;
if($logbook_loans != ''):
$faux_array[] = "797";
endif;
if($easy_money != ''):
$faux_array[] = "803";
endif;
foreach($faux_array as $faux_array_value):
$faux_array_all .= $faux_array_value . ',';
endforeach;
echo $faux_array_all;
$args = array
(
'posts_per_page' => 10,
'post_type' => 'lender',
'order' => 'ASC',
'orderby' => 'date',
'post__in' => array($faux_array_all)
);
?>
Mmh for one, you can avoid the loop with just:
$faux_array_all = implode(',', $faux_array);
which would also solve the trailing comma proble.m.
On the other hand, you pass an array to post__in that only contains one element (the string). I think what you really want is
'post__in' => $faux_array
as $faux_array is already an array with IDs.
Read about Post & Page Parameters, there you can see that you need to pass an array of post IDs to the function, not an array with one string value:
'post__in' => array(5,12,2,14,7) - inclusion, lets you specify the post IDs to retrieve
'post__in' => $faux_array
Try this, and if it doesn't work post the code that you manually make to work please.
Edited. Check it now.
You need to trim off the trailing comma
foreach($faux_array as $faux_array_value):
$faux_array_all .= $faux_array_value . ',';
endforeach;
if (substr($faux_array_all)-1,1) == ",") {
$faux_array_all = substr($faux_array_all,0,-1);
}
Related
I would like just to add conditionally 's' => $search_term to an array if there is a search term.
$args = array(
// if there is a $search_term then insert:
's' => $search_term
);
I know that I can write many arguments and then using an if statement outside the array but that is way is not what am wishing to do.
You need to do it outside the array as if not the key 's' will be declare anyway in the array (with an empty value if there is no a search term.
Try the following where we insert conditionally a new key / value pair in a defined array:
// Initialize (or define) the array variable
$args = array();
// IF + Condition
if( isset($search_term) && ! empty($search_term) ){
// Inserting in $args array a new key / value pair
$args['s'] = $search_term;
}
Or as explained before, with an always defined 's' key as follow:
$args = array(
's' => isset($search_term) && ! empty($search_term) ? $search_term : '';
);
What you propose cannot be accomplished. The PHP array function is used to declare the keys and values. So, when you write:
$args = array(
's' => $search_term
);
It will create the key 's'. You can do the following
$args = array(
's' => isset($search_term) ? $search_term : null
);
and query with isset($args['s']) to do what you describe, but IMO it is bad to rely on that behavior. isset returns false what array values are null.
The best way is as LoicTheAztec recommends, but you have your workaround here.
Ive been stressing alot with this php code and cant figure out why it does not work.. Stack overflow is kind of the my last resort.
First things first, here is my code:
$avar = "Name";
$args = array(
'category_name' => $avar
);
var_dump($args);
This code returns:
array (size=1)
'category_name' => null
So the question is, why doesnt it return "Name" instead of null and is there any way to give the array the value of the variable?
Please help me!
** Update **
Im sorry. Forgot I had the code inside a function. Here is the code I use. I put it inside a brand new document, and it still doesnt work. Only difference is now i get an error. (Im coding for wordpress, and i guess some warnings are disabled in order to tighten security). The code:
<?php
$avar = "SomeText";
function theFunction() {
$args = array(
'category_name' => $avar
);
var_dump($args);
}
theFunction();
?>
The code still works with strings.
<?php
$avar = "SomeText";
function theFunction() {
global $avar;
$args = array(
'category_name' => $avar
);
var_dump($args);
}
theFunction();
?>
I am working on a Wordpress project where I need to dynamically create a function (depending on which kind of template is used for a page or post) that retrieves the comments of each page in question.
So let's say I have pages within Wordpress with the IDs 100, 110, 120, 130, 140, 150 and out of these 3 are using the template called "blog" (e.g.: 100, 130 and 150).
So in order to retrieve the comments from these 3 pages with AJAX I need to create a function for each of them:
function GetComments100() { #### }
function GetComments130() { #### }
function GetComments150() { #### }
Here's the function code I need to create individually for each page (and which goes in between the function brackets above (instead of the ####):
$defaults = array( 'order' => 'DESC', 'post_id' => $functionID, 'post_type' => 'page', 'count' => false );
$comments = get_comments($defaults);
foreach($comments as $comment) :
echo "<div class='table-row' style='margin-bottom:1px'><div class='table-cell-1' style='width:110px;'>".$comment->comment_author.":</div><div class='table-cell-2'style='width:870px;'>".$comment->comment_content." <em><a>".$comment->comment_date." ... ".get_the_title($comment->comment_post_ID)." (".$comment->comment_post_ID.")</a></em></div></div>";
endforeach;
die($results);
In order to get the pages I use a loop-function which gives me the page ID as a variable (in my case its $functionID (also included in the array of my function above)).
I have already managed to dynamically create the functions with the following lines of code (I know "eval" is not a good choice but I didn't find any other solution):
$string = 'function ' . $functionName . "() {
####
}";
eval($string);
Now instead of the #### I need to integrate the actual function code starting with "$defaults = array(..." but obviously it has to be completely converted to a string - which is what I am struggling with.
Any help would be appreciated (again, I know using "eval" is not nice but so far I didn't find any other solution for this)
Have you tried using nowdoc for the function body? If you just need expanding $functionName, you can try something like this:
$string="function {$functionName}(){".<<<'END'
$defaults = array( 'order' => 'DESC', 'post_id' => $functionID, 'post_type' => 'page', 'count' => false );
$comments = get_comments($defaults);
foreach($comments as $comment) :
echo "<div class='table-row' style='margin-bottom:1px'><div class='table-cell-1' style='width:110px;'>".$comment->comment_author.":</div><div class='table-cell-2'style='width:870px;'>".$comment->comment_content." <em><a>".$comment->comment_date." ... ".get_the_title($comment->comment_post_ID)." (".$comment->comment_post_ID.")</a></em></div></div>";
endforeach;
die($results);
}
END;
eval($string);
I don't understand why you don't use one function per Template with a parameter like this:
public function getBlogComments($id){
//...
}
or one function which check the used Template
public function getComments($id){
// get Template of $id
//...
}
I have a usermeta set up for my users that saves favorite post to their profile. I am getting this usemeta(which keeps the post IDs in it). Once I get it, I have it in an one dimensional array. I want to display a list of their favorite posts. I have tried this:
$favorites //array of favorites, that has come from the databese
$query = new WP_Query( array( 'post__in' => array( 2, 5, 12, 14, 20 ) ) );
and it would work fine, if I hard coded the post IDs , but since it is an array I can't just pass in array such, it returns nothing.
$query = new WP_Query( array( 'post__in' => $favorites) );
it does not accept it, I also tried to implode the array in to a string as such:
$fav_list = implode("," , $favorites);
and i get this, which is exactly what I need as a string
"124,126,125,130,132,140,142", without the quotes. I would then use it as such:
$query = new WP_Query( array( 'post__in' => array($fav_list) ) );
But again it doesn't work, it returns nothing. Since the favorites list is being pulled from the usermeta and the user can change it, I can't hard code the list.
Can anyone help me? Is it even possible with WP_Query. Not sure why it is not taking the string or what I am doing wrong. I red through the Wordpress Documentation but haven't found a solution.
Thanks in advance.
Arrays don't get stored in the database as arrays. They get serialized. When you pull the array from the database you have to unserialize() it.
http://php.net/manual/en/function.unserialize.php
If you var_dump($favorites) right after it comes out of the database, you'll notice it's a weird-lookin' string and not an array. var_dump(unserialize($favorites)) will show you your original array.
Note: While this is probably a simple fix, I'm new to using arrays and am completely stumped.
I'm trying to save the data from a shortcode array via the Options API in WordPress, then call that array and use the data to create another array to hook into a plugin's function. It's a responsive slider plugin and I'm basically trying to attach a shortcode to it so I can create the slider on the backend and display it on the front end with a shortcode that looks like: [responsive_slider slider_name="imageslider"].
The implementation documentation can be found here, and here's my code:
function responsive_gallery_shortcode($atts, $content=null) {
extract(shortcode_atts( array('slider_name' => 'product_page') , $atts));
foreach ($slider_name as $value) {
update_option('_unique_slider_name', $value );
}
if(function_exists('show_flexslider_rotator'))
echo show_flexslider_rotator( $slider_name );
add_image_size( $slider_name , '550', '250', true );
}
add_shortcode('responsive_gallery', 'responsive_gallery_shortcode');
if (!function_exists('custom_set_flexslider_hg_rotators')) {
function custom_set_flexslider_hg_rotators() {
$slider_name = get_option('_unique_slider_name');
foreach ($slider_name as $value) {
$rotators = array();
$rotators[ $value ] = array( 'size' => $value );
return $rotators;
}
}
}
add_filter('flexslider_hg_rotators', 'custom_set_flexslider_hg_rotators', 9999);
I'm getting an "Invalid argument supplied for foreach()" error on both foreach functions. On the page where I have two shortcodes both errors show up twice. It seems as though $slider_name is a string instead of an array, but there's got to be a way to save it in the update_option() function so that it returns an array. I'm quite new to arrays, and I'm definitely struggling here. I've spent hours on this and have already received a little help on the WordPress side, but I'm not quite getting it.
As the shortcode attribute will arrive as a string, you need to convert it to an array first.
At the same time, as it has to be passed as a string, you'll need to use a separator so you can manage this.
And for all that, you'll need the PHP function explode.
$string = "one,two";
$array = explode( ',', $string );
var_dump( $array );
Results in:
array (size=2)
0 => string 'one' (length=3)
1 => string 'two' (length=3)
And
$string = "one";
$array = explode( ',', $string );
var_dump( $array );
Results in:
array (size=1)
0 => string 'one' (length=3)
PS: It's always worth to consult the PHP Manual and also the comments in each of its pages : http://www.php.net/manual/en/language.types.array.php
[update]
There are many issues with your original code, check the comments of this revised version:
function responsive_gallery_shortcode($atts, $content=null) {
extract(shortcode_atts( array('slider_name' => 'product_page') , $atts));
// Convert string into array
// Using comma as separator when writing the shortcode in the post
$array_slider = explode( ',', $slider_name );
// YOU DON'T NEED A `foreach` HERE
//foreach ($array_slider as $value) {
update_option('_unique_slider_name', $array_slider );
//}
// I DON'T KNOW WHAT THIS FUNCTIONS DOES
// But in any case, being $array_slider an array, maybe it should be inside a `foreach`
if(function_exists('show_flexslider_rotator'))
echo show_flexslider_rotator( $array_slider );
// THIS DOESN'T MAKE SENSE
// You're not supposed to be adding images sizes at each Shortcode call
// And you are dealing with an array
add_image_size( $slider_name , '550', '250', true );
}
add_shortcode('responsive_gallery', 'responsive_gallery_shortcode');
if (!function_exists('custom_set_flexslider_hg_rotators')) {
function custom_set_flexslider_hg_rotators() {
// The option was already saved as array, so we can work directly with it
$slider_name = get_option('_unique_slider_name');
// YOU DON'T WANT TO DECLARE THE VARIABLE AT EACH STEP OF THE LOOP
$rotators = array();
foreach ($slider_name as $value) {
$rotators[ $value ] = array( 'size' => $value );
}
// RETURN THE VALUE ONLY AFTER COMPLETING THE LOOP
return $rotators;
}
// PUT THE FILTER HOOK INSIDE if(!function_exists())
add_filter('flexslider_hg_rotators', 'custom_set_flexslider_hg_rotators', 9999);
}