Search post_like + search by taxonomy checkboxes in one loop - loops

Im pretty new in WP so pls forgive me my ignorance im trying to learn.
So I have two Wp_Query (search by typeing in searchbar and search by taxonomy checkboxes) and I dont know how to mix them... If one works second dont and its a cricle.
<?php
global $search_ingr;
if(isset($search_ingr)) {
global $loop;
} else {
$query_params = getQueryParams();
if(isset($query_params['search'])) {
$query_params['post_title_like'] = $query_params['search'];
unset($query_params['search']);
}
$loop = new WP_Query(array(
'numberposts' => 60,
'posts_per_page' => 60,
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'products',
'post_status' => 'publish'
));
}
?>
<?php if(isset($search)): ?>
<div class="search-matches"><h4>Wyniki wyszukiwania:</h4><hr></div>
<?php endif; ?>
<?php if ($loop->have_posts()) :?>
<?php while($loop->have_posts()) : $loop->the_post (); ?>
<span class="tooltip tooltip-effect-4">
<span class="tooltip-item">
<div class="product">
<a href="<?php the_permalink(); ?>">
<div class="product-thumbnail"><span class="helper"></span><?php the_post_thumbnail(); ?></div>
<div class="product-name"><?php the_title(); ?></div>
</a>
</div>
</span>
<a href="<?php the_permalink(); ?>">
<span class="tooltip-content clearfix">
<?php the_post_thumbnail(); ?>
<span class="tooltip-text"><?php the_title(); ?></span>
</span>
</a>
</span>
<?php endwhile; ?>
<?php endif; ?>
Pretty long peace of code, Im pasting it with loop as well and above that I have search box and taxonomy list.
Additionally when I remove this:
// $loop = new WP_Query(array(
// 'numberposts' => 60,
// 'posts_per_page' => 60,
// 'orderby' => 'title',
// 'order' => 'ASC',
// 'post_type' => 'products',
// 'post_status' => 'publish'
// ));
Both searches works great(but I cant control post order and number of posts).
Any help on that?

The proper way to modify the wordpress loop would be like this.
Try this instead of the first block of PHP on top:
<?php
$search = get_query_var('s');
$loop = new WP_Query(array(
'numberposts' => 60,
'posts_per_page' => 60,
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'products',
'post_status' => 'publish',
's' => $search
));
?>
The potential problem is that you are using functions and parameters which aren't native to wordpress - getQueryParams() isn't a wordpress function and the WP_Query function doesn't accept a parameter with name 'post_title_like'. If this code works then you might be using some plugin for the search functionality in which case you would have to override the plugin behavior, not the default wordpress query.

Thanks a lot! Really appreciate youre help but it didnt resolve my problem.
I will try another way
This piece of code work perfectly for both searches but I need to change number of posts above limit of 10(thats why I started to messing with this code):
<?php
global $search_ingr;
if(isset($search_ingr)) {
global $loop;
} else {
$query_params = getQueryParams();
if(isset($query_params['search'])) {
$query_params['post_title_like'] = $query_params['search'];
unset($query_params['search']);
}
$loop = new WP_Query($query_params);
}
?>
And the getQueryParams() function:
function getQueryParams(){
global $query_string;
$parts = explode('&', $query_string);
$return = array();
foreach($parts as $part){
$tmp = explode('=', $part);
$return[$tmp[0]] = trim(urldecode($tmp[1]));
}
return $return;
}

Related

CAKEPHP 4: I cannot upload many files at the same time

Goodnight (or good morning),
I trying to upload multiple files at the same time. I am following the cookbook instructions to build the solution. I always got first file (not and array of files).
Here is my view code...
<?php
/**
* #var \App\View\AppView $this
* #var \App\Model\Entity\Upload $upload
*/
?>
<div class="row">
<aside class="column">
<div class="side-nav">
<h4 class="heading"><?= __('Actions') ?></h4>
<?= $this->Html->link(__('List Uploads'), ['action' => 'index'], ['class' => 'side-nav-item']) ?>
</div>
</aside>
<div class="column-responsive column-80">
<div class="uploads form content">
<?= $this->Form->create($upload, ['type' => 'file']) ?>
<fieldset>
<legend><?= __('Add Upload') ?></legend>
<?php
echo $this->Form->control('name');
echo $this->Form->control('document_type_id', ['options' => $documentTypes]);
echo $this->Form->control('period_id', ['options' => $periods]);
echo $this->Form->control('user_id', ['options' => $users]);
echo $this->Form->control('documents', ['type' => 'file', 'label' => __('Choose PDF Files'), 'accept' => 'application/pdf', 'multiple' => 'multiple']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>
And here is my controller code...
public function add()
{
$upload = $this->Uploads->newEmptyEntity();
if ($this->request->is('post')) {
$upload = $this->Uploads->patchEntity($upload, $this->request->getData());
if ($this->Uploads->save($upload)) {
if (!is_dir($this->Parameters->findByName('document_directory')->first()->toArray()['value'] )) {
mkdir($this->Parameters->findByName('document_directory')->first()->toArray()['value'], 0776, true);
}
$documents = $this->request->getData('documents');
$this->loadModel('Dockets');
$dockets = $this->Dockets->findByDocketStateId(1);
$documents_ok = 0;
$documents_nok = 0;
$dockets_without_document = 0;
foreach($documents as $documents_key => $document_to_save)
{
foreach($dockets as $dockets_key => $docket)
{
$contents = file_get_contents($document_to_save);
$pattern = str_replace('-', '', $pattern);
$pattern = str_replace('', '', $pattern);
$pattern = preg_quote($docket->cuit, '/');
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
$documentsTable = $this->getTableLocator()->get('Documents');
$document = $documentsTable->newEmptyEntity();
$document->upload_id = $upload->id;
$document->document_type_id = $upload->document_type_id;
$document->period_id = $upload->period_id;
$document->docket_id = $docket->id;
$document->user_id = $this->getRequest()->getAttribute('identity')['id'];
if ($documentsTable->save($document)) {
if (!is_dir($this->Parameters->findByName('document_directory')->first()->toArray()['value'] )) {
mkdir($this->Parameters->findByName('document_directory')->first()->toArray()['value'], 0776, true);
}
$fileobject = $this->request->getData('document');
$destination = $this->Parameters->findByName('document_directory')->first()->toArray()['value'] . 'document_' . $document->id . '.pdf';
// Existing files with the same name will be replaced.
$fileobject->moveTo($destination);
}
$this->Flash->error(__('The document could not be saved. Please, try again.'));
$documents_ok = $documents_ok + 1;
unset($dockets[$dockets_key]);
unset($documents[$documents_key]);
break;
}
}
}
if(!empty($documents)){
//print_r($documents);
$documents_nok = count($documents);
unset($documents);
}
if(!empty($dockets)){
$dockets_without_document = count($dockets);
unset($dockets);
}
$message = __('There were processed ') . $documents_ok . __(' documents succesfully. ') . $documents_nok . __(' documents did not math with a docket. And ') . $dockets_without_document . __(' active dockets ddid not not have a document.');
$this->Flash->success(__('The upload has been saved. ') . $message);
return $this->redirect(['action' => 'view', $upload->id]);
}
$this->Flash->error(__('The upload could not be saved. Please, try again.'));
}
$documentTypes = $this->Uploads->DocumentTypes->find('list', ['keyField' => 'id',
'valueField' => 'document_type',
'limit' => 200]);
$periods = $this->Uploads->Periods->find('list', ['keyField' => 'id',
'valueField' => 'period',
'limit' => 200]);
$users = $this->Uploads->Users->find('list', ['keyField' => 'id',
'valueField' => 'full_name',
'conditions' => ['id' => $this->getRequest()->getAttribute('identity')['id']],
'limit' => 200]);
$this->set(compact('upload', 'documentTypes', 'periods', 'users'));
}
Can you help me to understand what I doing wrong?
Thanks,
Gonzalo
When using PHP, multi-file form inputs must have a name with [] appended, otherwise PHP isn't able to parse out multiple entries, they will all have the same name, and PHP will simply use the last occurrence of that name.
echo $this->Form->control('documents', [
'type' => 'file',
'label' => __('Choose PDF Files'),
'accept' => 'application/pdf',
'multiple' => 'multiple',
'name' => 'documents[]',
]);
Furthermore the following line:
$fileobject = $this->request->getData('document');
should probably be more like this, as there a) is no document field and b) even if there were, you most likely wouldn't want to process the same file over and over again:
$fileobject = $documents[$documents_key];
Also make sure that you have proper validation in place for the uploaded files, even if you don't seem to use the user provided file information, you should still make sure that you've received valid data!

WP Query inside taxonomy.php kills the standard loop

I have made a custom taxonomy archive page called taxonomy-country.php. The file runs perfectly and loops through the current country and displays the posts within it.
Above this loop on the same templeate I want to display a map of all the post locations using Advanced Custom Fields. I've used the code before with no problems but not in an archive file, however when used at the top of the template the map and markers show fine but the standard archive loop no longer displays.
What is wrong with the wpquery that it kills the loop after it? Or is there another reason I can't run he query above the normal loop on an archive page?
<?php
// WP_Query arguments
$args = array (
'post_type' => 'home',
'order' => 'ASC',
'orderby' => 'title',
'posts_per_page' => '-1',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) { ?>
<div class="acf-map">
<?php while ( $query->have_posts() ) {
$query->the_post(); ?>
<?php
$location = get_field('location');
if( !empty($location) ):
?>
<div class="acf-map">
<div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">
<h2 class="name"><?php the_title(); ?></h2>
<strong class="number"><?php echo do_shortcode('[mrp_rating_result rating_form_id="2"]'); ?></strong>
</div>
</div>
<?php endif; ?>
<?php }
} else {
// no posts found
}
// Restore original Post Data
wp_reset_query() ?>
UPDATE:
Just found out this should be shorter alternative:
wp_reset_postdata()
ORIGIONAL:
This line killed it:
// Restore original Post Data
wp_reset_query() ?
Reason: You did not use main $wp_query, hence $query->the_post() did not interfere with the current index of $wp_query. Resetting it will cause the main loop to restart.
Reference: https://codex.wordpress.org/Function_Reference/wp_reset_query
A safer way is to:
Before the category loop:
global $post;
$temp_post = $post;
After the category loop:
$post = $temp_post;
Just 3 lines and it should work.
Cheers!
As per above answer you have to store the $post in in temporary variable and restore it before wp_reset_query()
example function code look like below
function cd_meta_box_cb_hotel( $post )
{
global $post;
$temp_post = $post;
$selected=get_post_meta($post->ID, 'hotel_location_id',true);
$mquery = new WP_Query(array(
'post_type' => 'custom posttype',
'post_status' => 'publish',
'posts_per_page' => -1,
));
while ($mquery->have_posts()) {
$mquery->the_post();
// doing what you need
}
**$post = $temp_post;
wp_reset_query();**
}

simple blog with croogo

I is not What is the problem, I made a simple blog in Croogo, the problem is it is not adding or modifying or delete, because Arabic language ??
function add in controller
`public function admin_add() {
$this->set('title_for_layout', __('Add Part'));
if (!empty($this->request->data)) {
$this->Part->create();
if ($this->Part->save($this->request->data)) {
$this->Session->setFlash(__('The Part has been saved'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));//, $this->Part->id));
} else {
$this->Session->setFlash(__('The Part could not be saved. Please, try again.'), 'default', array('class' => 'error'));
}
}
}`
=>
model
`class Part extends AppModel {
public $name = 'Part';
var $belongsTo = array(
'Market' => array(
'className' => 'Market',
'foreignKey' => 'market_id',
)
);
protected $_displayFields = array(
'id',
'num_part',
'prix_part',
'prop_Pledge',
'prix_Pledge',
);
}
`
add view
<?php $this->extend('/Common/admin_edit'); ?>
<?php echo $this->Form->create('Part');?>
<fieldset>
<div class="tabs">
<ul>
<li><span><?php echo __('Part'); ?></span></li>
<?php echo $this->Layout->adminTabs(); ?>
</ul>
<div id="role-main">
<?php
echo $this->Form->label('num_part', 'العدد : ');
echo $this->Form->input('num_part',array('label' => false ));
echo $this->Form->label('prix_part', 'االمبلغ : ');
echo $this->Form->input('prix_part',array('label' => false ));
echo $this->Form->label('prop_Pledge', 'إقتراح التعهد : ');
echo $this->Form->input('prop_Pledge',array('label' => false ));
echo $this->Form->label('prix_Pledge', 'مبلغ التعهد : ');
echo $this->Form->input('prix_Pledge',array('label' => false ));
?>
</div>
<?php echo $this->Layout->adminTabs(); ?>
</div>
</fieldset>
<div class="buttons">
<?php
echo $this->Form->end(__('Save'));
echo $this->Html->link(__('Cancel'), array(
'action' => 'index',
), array(
'class' => 'cancel',
));
?>
</div>
message error : The requested address was not found on this server.
I don't think it is because of Arabic language because when you do :
echo $this->Form->label('prop_Pledge', 'إقتراح التعهد : ');
The second parameter is a text. I don't know which Cake version you're using but I think that the first field should be Part.prop_Pledge (Cake v3).
I suggest you to try to use debug() and exit to see where is the real problem or try to put remove arabic characters to see if this is the reason of you're problem.
Just a question where is your $this->Form->create() in view ?
line added to the database successfully but does not retoure to index
it displays an error message
Could you print the message error hello21 please ?
Hope this will help you.

Wordpress query_post array with Advanced Custom Fields (probably a simple solution)

Working on a Wordpress site and was wondering if anyone could point me in the right direction.
I have the following query_post which filters posts on my template and its working great.
query_posts( array( 'category_name' => 'galoretv', 'post_type' => 'post', 'paged'=>$paged, 'showposts'=>0, ) );
How would I append this to include a check for a specific value from Advanced Custom Fields?
Posts in this category have a radio button with three options 'primary' 'secondary' 'standard'
I want to be able to check against each value i.e if you belong in 'galoretv' and 'standard' do this.
I have the page executing and sorting with the parameters above, just not sure how to add the ACF value. I was able to get it to work using the sticky option but thats gonna work cause i need to have primary and secondar optionality. This is show i had it working with the sticky.
query_posts( array( 'category_name' => 'galoretv', 'post_type' => 'post', 'paged'=>$paged, 'showposts'=>0, 'post__in'=>get_option('sticky_posts')) );
The radio buttons field is called 'landing-grid-placement'
Any thoughts? Been checking the documentation, can't figure it out.
http://www.advancedcustomfields.com/docs/field-types/checkbox/
Thought this would work but it didn't
query_posts( array( 'category_name' => 'galoretv', 'post_type' => 'post', 'paged'=>$paged, 'showposts'=>0, 'landing-grid-placement' => 'primary') );
Any help would be greatly appreciated. This is probably a simple syntax issue but its eluding me and causing me a lot of issues. Been searching for an answer but haven't got it right yet. Thank you advance to whoever reads this and a double thank you to anyone who contributes a solution.
APPENDED CODE PER NOTE BELOW
<?php
$args = array(
'post_type' => 'post',
'category-slug' => 'models-galore',
'showposts'=>1,
'meta_query' => array(
array(
'key' => 'grid_location',
'value' => 'primary',
'compare' => '=',
'type' => 'CHAR'
)
)
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts()) {
$query->the_post();
?>
<li class="span8">
<div class="thumbnail">
<?php echo get_the_post_thumbnail( get_the_ID(), 'media-large-thumb' ); ?>
<h3>
<?php the_title(); ?>
</h3>
</div>
</li>
<?php
}
}
?>
You can do this with a meta_query
Here's the doc
And here's an example:
$args = array(
//...
'post_type' => 'post',
'paged'=>$paged,
//...
'meta_query' => array(
array(
'key' => 'landing-grid-placement',
'value' => 'primary',
'compare' => '=', //default
'type' => 'CHAR' //default
)
)
);
//This is the shoposts option (deprecated since 2.1, now use posts_per_page)
$args['posts_per_page'] = -1; //-1 = infinite
//to add taxonomy
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'galoretv'
)
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts()) {
$query->the_post();
?>
<li class="span8">
<div class="thumbnail">
<?php echo get_the_post_thumbnail( get_the_ID(), 'media-large-thumb' ); ?>
<h2>
<?php the_title(); ?>
</h2>
</div>
</li>
<?php
}
}
Maybe there is a simpler solution for you :
$args = array(
//...
'post_type' => 'post',
'paged'=>$paged,
//...
'meta_key' => 'landing-grid-placement',
'meta_value' => 'primary',
'meta_compare' => '=' //default
)
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts()) {
$query->the_post();
//do what you would normally do in your loop
}
}

cakephp 2.2.2 pagination search condition

I am trying to add pagination in CakePHP 2.x with condition search in a form. However, in the View it doesn't give the next page with my condition. Here is my code:
Controller
public function result($palabraclave = null)
{
$this->layout = 'tempart';
$this->paginate = array(
'limit' => 5,
'order' => array(
'Articulo.created' => 'desc'),
'conditions'=>array("titulo like ?"=>"%".$this->data['Paginas']['palabraclave']."%")
)
$data = $this->paginate('Articulo');//Consulta a la base de datos
$this->set(compact('data'));
}
If I click "next" to see the next page result of the search, it doesn't pass on the pagination condition from page 1 to page 2. :(
View:
<div style="display: inline-block; width:70%;" id="test">
<?php foreach ($data as $da): ?>
<br />
<article>
<?php echo $this->Html->image('article_preview/mini_'.$da['Articulo']['imagen'], array('alt' => 'Hospital-Excel'))?>
<div style="text-align:left;">
<?php echo $this->Html->link("<h6 class='artnombre'>".$da['Articulo']['titulo']."<h6>", array('class'=>"artnombre",'action'=> 'articulo',$da['Articulo']['id']),array('escape' => false)); ?>
</div>
<br />
<p>
<?php echo $da['Articulo']['descripcion']; ?> <?php echo $this->Html->link('Read more ....', array('action'=> 'articulo',$da['Articulo']['id'])); ?>
<h5></h5>
</p>
<div class="puntoshorizontal" style="clear"></div>
</article>
<?php endforeach; ?>
<div style="text-align:center">
<?php
// Shows the page numbers
// Shows the next and previous links
echo $this->Paginator->prev('« Back', null, null, array('class' => 'disabled')) . " |";
echo $this->Paginator->numbers(). "| ";
echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled'));
echo "<br />";
echo $this->Paginator->counter();
// prints X of Y, where X is current page and Y is number of pages
?>
</div>
</div>
a way to persist your search params on each page you should do the following:
After you post data, in your method you have $this->data['Paginas']['palabraClave'] then save it the the session. So in each subsequent call to /resultados/pag1,2,..n you get the value of palabra clave from the session.
Finally you would get something like:
public function resultados(){
$conditions = array();
if($this->Session->check('conditions')){
$conditions = $this->Session->read('conditions');
}
if(isset($this->data)){
$conditions = array("titulo LIKE" => "%".this->data['Paginas']'palabraclave']"%",));
//save to the session
$this->Session->write('conditions',$conditions);
}
$data = $this->painate('Articulo',$conditions);
$this->set('data');
}
This may need some adjust but the idea I think is clear.
Set your paginate conditions when calling the paginate method, like this:
$data = $this->paginate('Articulo', array(
"titulo LIKE" => "%" . $this->data['Paginas']['palabraclave'] . "%",
));
as opposed to in the paginate property.
this is example:
1: pass all URL arguments to paginator functions
$this->Paginator->options(array('url' => $this->passedArgs));
2: Common mistake: not keep condition search with paginate
if($this->data){
$this->passedArgs = array(
'name' => $this->data[‘User’]['name']
);
}else{
if(isset($this->passedArgs['name'])){
$this->data[‘User’]['name'] = $this->passedArgs['name'];
}else{
$this->data[‘User’]['name'] = ;
}
}

Resources