Wordpress, how to make search for posts using get method? - php

So I am building a WordPress theme for myself to meet my needs, so what I am looking for now is make a search using a get method in php.
If my url is something like this :
http://www.MyWordPressWebsite.com/search.php?string=Bananas+and+apples
In my search.php I would like to do something like this:
string = $_GET["string"];
$fruits_args = array(
'post_type' => 'fruits',
'posts_per_page' => -1,
'cat' => 'fruits'
);
$fruits = new WP_Query($fruits_args);
So how do I making the loop related to the string that I get from the the get method ?
comparing the search string the the post type, category and post title would be enough.

use query_posts() instead and Wordpress will handle the search with those parameters. You can add as many parameters as you want.
Example:
<?php $my_post_type = (get_query_var('my_post_type')) ? get_query_var('my_post_type') : false;?>
<?php query_posts(array('post_type' => $my_post_type));?>
<?php //Normal loop here ?>
For more info visit https://codex.wordpress.org/Function_Reference/query_posts
I hope this help

Related

WordPress post search with ignoring apostrophe

I am trying to search posts in wp_posts table
$searchValue = $request->get_param("s");
$wpQueryPosts = new \WP_Query([
'post_type' => 'post',
'posts_per_page' => -1,
'cat' => 9,
's' => $searchValue,
]);
$postsPosts = $wpQueryPosts->get_posts();
The problem is when I search word with apostrophe it's not searched properly. If I search don I get proper results, when I search don't I don't get any results. Even though I know there are posts with don't in their title and content. I found many similar questions but none of them has any clear answer.
Also how can I get same results for both dont and don't
the problem is that if word in database contains apostrophe, it doesn't appear in results
This should do the job:
$searchValue = html_entity_decode( $searchValue, ENT_QUOTES );

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

Wordpress Multiple post from a post 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.

Is it possible to page and sort two different models in the same view in CakePHP?

I want to do something very straight forward and simple. I want to have two different sets of paginated data on the same page. The two different sets depend on different models. For discussion's sake we'll say they are Image and Item.
I can set up two pagers for two models, and get the correct set of objects. I can get the correct pager links. But when it comes to actually following the links to the parameters, both pagers read the parameters and assume they apply to them.
It winds up looking something like this:
$this->paginate = array (
'Item'=>array(
'conditions'=>array('user_id'=>$id),
'limit' => 6,
'order' => array(
'Item.votes'=>'desc',
'Item.created'=>'desc'
),
'contain'=>array(
'User',
'ItemImage' => array (
'order'=>'ItemImage__imageVotes desc'
)
)
),
'Image'=>array(
'limit'=>6,
'contain'=>array(
'User',
'ItemImage'=>array('Item'),
),
'order'=>array(
'Image.votes'=>'desc',
'Image.views'=>'desc'
),
'conditions'=>array(
'Image.isItemImage'=>1,
'Image.user_id'=>$id
)
)
);
$this->set('items', $this->paginate('Item'));
$this->set('images', $this->paginate('Image'));
That's in the controller. In the view I have sort links that look like this:
<div class="control"><?php echo $this->Paginator->sort('Newest', 'Image.created', array('model'=>'Image')); ?></div>
However, that yields a link that looks like this:
http://localhost/profile/37/page:1/sort:Image.created/direction:asc
There's nothing in there to tell the paginator which model I intend to sort. So when I click on the link it attempts to sort both models by Image.created. The result is an error, because Item cannot be sorted by Image.created. Is there something I'm doing wrong? Or is this something that isn't supported by CakePHP's paginator?
You'll need to override the paginate method for the Model of the Controller of that page.
I did something similar, maybe this snippet will help:
function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array())
{
$pageParams = compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive', 'group');
$this->contain('ModuleType', 'NodeDescriptor');
$pageItems = $this->find('all',$pageParams);
$pagesOut = array();
foreach($pageItems as $pageItem)
{
$status = $pageItem['SiteAdmin']['status_id'];
$moduleInfo = null;
$nodeTitle = $pageItem['NodeDescriptor']['title'];
$published = $pageItem['NodeDescriptor']['published'];
$pageitemID = $pageItem['SiteAdmin']['id'];
$moduleId = $pageItem['SiteAdmin']['module_id'];
$contName = $pageItem['ModuleType']['controller'];
if($moduleId)
{
$thisModel = ClassRegistry::getObject($moduleType);
$thisModel->contain();
$moduleInfo = $thisModel->read(null,$moduleId);
$moduleInfo = $moduleInfo[$moduleType];
}
$pagesOut[] = array(
'status'=>$status,
'node'=>$nodeTitle,
'published'=>$published,
'info'=>$moduleInfo,
'module_id'=>$moduleId,
'contName'=>$contName,
'pageitem_id'=>$pageitemID);
}
return $pagesOut;
}
By doing it this way, you gain control over the parameters passed to paginate, so you can pass model specific data, control flags etc.
The easiest solution would be to implement both grids as elements that fetch their own data and use AJAX to load the elements into the page.
The only other option would be to modify the params so you pass the params for both grids to each grid when sorting or stepping through pages. The code posted by Leo above is a good start. You can prepend the Model key from the paginate array onto each named param and make sure you pass all url params to the paginate function and you should be headed in the right direction.

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