PHP function not working as expected - php

<?php
function getPosts($showposts,$tags, $thumb_key="thumb_300x166", $thumb_class, $thumb_width="300", $thumb_height="166") {
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query('tag=$tags&showposts=$showposts');
while ($wp_query->have_posts()) {
$wp_query->the_post();
echo '<div class="entry"><div class="left">';
if ( function_exists( 'get_the_image' ) ) {
$defaults = array(
'custom_key' => array( '$thumb_key' ),
'image_class' => '$thumb_class',
'image_scan' => true,
'width' => '$thumb_width',
'height' => '$thumb_height'
);
get_the_image($defaults); // thumbnail
} // end if
echo '</div>
<div class="right">
<h3>'.the_title().'</h3>'
.the_excerpt().'</div></div>';
} // end while
}
getPosts($showposts=5,$tags="news",$thumb_class="review-thumb");
?>
I don't understand why this wordpress query function isn't working. I doesn't return/print anything at all.

I have never used Wordpress, but I see one problem that might be the cause of this.
Which is that if you use single quotes, such as on the following line:
$wp_query->query('tag=$tags&showposts=$showposts');
$tags and $showposts are not processed and are inserted into the string literally. If you want your string to contain the values of $tags and $showposts, use double quotes, like this:
$wp_query->query("tag=$tags&showposts=$showposts");
The same goes for the array passed to get_the_image.
edit: Additionaly, your function call looks weird. You're using syntax similar to when you're providing default values for arguments, but a regular function call will look something like this:
getPosts(5, "news", "review-thumb");

Related

Cant give php array a value using a variable

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();
?>

Get all WordPress sidebars

I'm trying to get a list with all registered sidebars using $wp_registered_sidebars but the global variable returns an empty array.
function get_sidebars() {
global $wp_registered_sidebars;
$sidebar_options = array();
foreach ($wp_registered_sidebars as $sidebar)
{
$sidebar_options[$sidebar['id']] = $sidebar['name'];
}
return $sidebar_options;
}
$fields['sidebar_settings'] = array(
'active' => array(
...
'values' => get_sidebars(),
...
),
);
Why is the global variable empty and is there another way to store all registered sidebars in an array?
Please try this
https://wordpress.stackexchange.com/questions/13450/list-all-sidebar-names
you get all the sidebar name lists
Heres some functions that you could be looking for:
dynamic_sidebar
wp_get_sidebars_widgets
See this: http://codex.wordpress.org/Sidebars . There's also some good information.

Putting correct php-code within eval()-string

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

yii ajaxLink is not passing variable to controller

I am trying to pass a variable from an ajaxLink into my controller but my controller is not getting the variable.
//view
$ids = Yii::app()->storedData->getIds();
foreach($ids as $id) {
echo 'ID '.$id .'<br />';
echo CHtml::ajaxLink(
'remove',
array('/storedInfo/remove'),
array(
'data' => array('removeItem' => $id),
));
}
//controller
public function actionRemove() {
var_dump($_GET['removeItem']); // RETURNS string(0) ""
die();
}
The ajax array you're passing to CHtml::ajaxLink ends up taking the whole array and passing it to CJavaScript::encode().
As you mentioned in your comments, the $id you were using to build your data array was a PHP object. When this got to CJavaScript::encode, things got wonky, and the results weren't what you were expecting. Extracting a string or numeric value from $id, rather that passing the whole object should take care of this, e.g.:
'data' => array('removeItem' => $id->value) // obviously you'll need to use the proper key to get the value
Or maybe something like this depending on the data structure:
'data' => array('removeItem' => settype($id, 'string'),
I edited out my answer because i admit it was not what the original asker wanted but for the sake of the comments, i leave my code here
$ids = Yii::app()->storedData->getIds();
foreach($ids as $id) {
echo 'ID '.$id .'<br />';
echo CHtml::ajaxLink(
'remove',
array('/storedInfo/remove', array('removeItem' => $id)),
);
}
Looks like CHtml::ajaxLink takes more parameters than you're sending.
public static string ajaxLink(string $text, mixed $url, array $ajaxOptions=array ( ), array $htmlOptions=array ( ))
Do you need to send along some $text before the $url?

PHP & Array question

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);
}

Categories