Clear or reset the wordpress posts pagination while changing filters - filter

I think it is simple, but I don't get it.
This is my filter:
<form class='post-filters'>
<select name="filter">
<?php
$filter_options = array(
'houses' => 'Houses',
'hotels' => 'Hotels',
);
foreach( $filter_options as $value => $label ) {
echo "<option ".selected( $_GET['filter'], $value )." value='$value'>$label</option>";
}
?>
</select>
<input type='submit' value='Filter!'>
</form>
Related PHP to apply the filter to the wordpress query:
<?php
global $destinations;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$destinations = new WP_Query([
'paged' => $paged,
'location' => $location,
'category_name' => urldecode(get_query_var('filter')),
'posts_per_page' => 6
]);
?>
If I do select my "filter" and the result has more than six entries, I use next_posts_link() to see the next six results. The problem is now, if I'm on page 2 or 3 and the other filter has less than e.g. 6 entries, I will see no results while changing my filter.
How do I clear the get variable (/page/2/) while changing my filter?
Example:
category/subcategory/subsubcategory/page/3/?filter=houses
Now I select "filter" hotels
category/subcategory/subsubcategory/page/3/?filter=hotels
and the "/page/3" will not be cleared. So I can not see some posts.

It has been anwsered here:
https://wordpress.stackexchange.com/a/264266
function get_nopaging_url() {
$current_url = $_SERVER[REQUEST_URI];
$pattern = '/page\\/[0-9]+\\//i';
$nopaging_url = preg_replace($pattern, '', $current_url);
return $nopaging_url;
}
You could use this function to remove the pagination in your urls with filters.
See example:
<a href="<?php echo get_nopaging_url(); ?>?filter=houses">

Related

Filter posts by their post-type with dropdown menu

I want to filter posts by their post-type.
therefore I have created a dropdown menu where I can select one or multiple post-types.
My question now is: How do I get functionality for my dropdown, because I dont't know how to corespond with the database when the element is in the frontend.
This is my Dropdown-Menu
Using ajax you can filter post.
This is my code for filter post by category (filter post by multiple category selection)
ajax code
<script type="text/javascript">
$('.categorytag').click(function(){
var cokeValue = //you need to pass array of post category id
var data = {
action: 'get_partiblog',
foo: cokeValue
};
$.post('/wp-admin/admin-ajax.php',data,function(response){
$('#filteredblog').html(response);
});
})
</script>
php code
<?php
add_action('wp_ajax_get_partiblog','Getblogcatwise');
add_action('wp_ajax_nopriv_get_partiblog','Getblogcatwise');
function Getblogcatwise(){
$catids = $_POST['foo'];
foreach($catids as $catid){
$args = array(
'post_type'=> 'post',
'orderby' => 'ID',
'category_name' => $catid,
'post_status' => 'publish',
'order' => 'DESC',
'posts_per_page' =>-1 // this will retrive all the post that is published
);
$result = new WP_Query( $args );
if ( $result-> have_posts() ) :
while ( $result->have_posts() ) : $result->the_post();
$link = get_permalink();
echo '<a href="'.$link.'" target="_blank">';
echo '<div class="service-wrapper" style="border:1px solid #367bae;">';
/* if ( has_post_thumbnail() ){
echo '<div><img src="'.the_post_thumbnail("thumbnail").'" alt="Image Missing" rel="lightbox"></div>';
}else{
echo '<div><img src="https://uae.microless.com/cdn/no_image.jpg" alt="" rel="lightbox"></div>';
}*/
$title= get_the_title();
echo '<center><div style="color:#367bae;font-size:22px;font-weight:700;position: relative;margin-top: 25%;padding:5%;">'.$title.'</div></center>';
echo '<div class="service-wrapper-inner">';
//$title= get_the_title();
//echo '<h3>'.$title.'</h3>';
echo '<center><i style="font-size:18px;color:#fff;-webkit-transition: 1s;-moz-transition: 1s;-ms-transition: 1s;-o-transition: 1s; transition: 1s;" class="fa fa-bars"></i></center>';
$excerpt= the_excerpt();
echo '<div class="description"><p>'.$excerpt.'</p></div></div></div></a>';
endwhile;
endif; wp_reset_postdata();
}
}
?>

Breadcrumbs links not showing correct url

I am creating some bread crumbs for my folders. When I click on the 2nd bread crumb link it does not go to the correct URL
The previous URL shows "test"
http://localhost/project/admin/common/test?directory=test/sub
It should show
http://localhost/project/admin/common/test?directory=test
Inspector Output
<ul class="breadcrumb">
<li>Catalog</li>
<li>test</li>
<li>sub</li>
</ul>
On view
<ul class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<li><?php echo $breadcrumb['text']; ?></li>
<?php } ?>
</ul>
Question: How can I make sure the previous URL to shows the before folder correct URL.
I generate my breadcrumbs on my controller
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => 'Catalog',
'href' => base_url('admin/common/test')
);
$directory_names = explode('/', $this->input->get('directory'));
foreach ($directory_names as $directory_name) {
$data['breadcrumbs'][] = array(
'text' => $directory_name,
'href' => base_url('admin/common/test?directory=' . $this->input->get('directory'))
);
}
Thanks to a solution now I found on another forum I will post on here to share
https://forum.codeigniter.com/thread-68653-post-346110.html#pid346110
$directory_names = explode('/', $this->input->get('directory'));
$directory_done = '';
foreach ($directory_names as $directory_name) {
$directory_done .= ($directory_done <> ''? '/':'').$directory_name;
$data['breadcrumbs'][] = array(
'text' => $directory_name,
'href' => base_url('admin/common/test?directory=' . $directory_done)
);
}

How can i insert multiple arrays into mysql database using codeginiter?

What i want is, i have a uniq id call num i want insert mutiple description for that unique num. i have a form to add fileds dynamically so i can add fields as much i want. when i try to insert one row data its works perfectly when i try to insert more than one row data it doesn't work.
My View page :
<form name="codexworld_frm" action="" method="post">
<div class="field_wrapper">
<input type="text" name="num" value=""/><br />
<input type="text" name="description[]" value=""/><input type="text" name="voucher_no[]" value=""/><input type="text" name="price[]" value=""/>
<img src="<?php echo base_url('images/add-icon.png'); ?>"/>
</div>
<input type="submit" name="submit" value="SUBMIT"/>
</form>
My Controller :
$data = array(
'no' => $this->input->post('num'),
'descriptions' => $this->input->post('description'),
'voucher' => $this->input->post('voucher_no'),
'des_price' => $this->input->post('price'),
);
$this->multi_model->form_insert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('multi_view', $data);
My Model:
function form_insert($data){
$this->db->insert('tbl_description', $data);
}
if i use foreache loop into my model i think it will work but i how do i use ?
When i use print_r() function this is out put
1001
Array
(
[0] => description1
[1] => description2
[2] => description3
)
Array
(
[0] => voucher 1
[1] => voucher 2
[2] => voucher 3
)
Array
(
[0] => 100
[1] => 200
[2] => 300
)
see this link it is use multiple insert without loop or you can use your foreach loop in controller count description post and go through it.
$data = array();
$count = count($this->input->post['description']);
for($i=0; $i < $count; $i++) {
$data[] = array(
'no'=>$this->input->post('num'),
'descriptions' => $this->input->post['descriptions'][$i],
'voucher' => $this->input->post['voucher'][$i],
'des_price' => $this->input->post['des_price'][$i],
);
}
$this->db->insert_batch('tbl_description', $data);
Hope this will helps you..
Controller
//if voucher_no is required..
$voucher_no = $this->input->post('voucher_no');
$count = count($voucher_no);
if ($count > 0) {
for ($i = 0; $i < $count; $i++) {
if (!empty($voucher_no[$i])) {
$data = array(
'no' => $this->input->post('num'),
'descriptions' => $this->input->post('description')[$i],
'voucher' => $this->input->post('voucher_no')[$i],
'des_price' => $this->input->post('price')[$i],
);
$this->multi_model->form_insert($data);
}
}
}
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('multi_view', $data);
Let us know the results..
change model as following.
function form_insert($data){
foreach($data['description'] as $key=>$des)
{
$savedata = array(
'no' => $data('no'),
'descriptions' => $des,
'voucher' => $data['voucher'][$key],
'des_price' => $data['dec_price'][$key],
);
$this->db->insert('tbl_description', $savedata);
}
}
you can insert object wise.
in your controller:-
$value=$this->input->post('num');
$count=count($val);
for($i=0; $i<$count; $i++){
$data['no']=$this->input->post('num')[$i];
$data['description']=$this->input->post('description')[$i];
$data['voucher']=$this->input->post('voucher')[$i];
$data['prize']=$this->input->post('prize')[$i];
$this->multi_model->form_insert($data);
}

CakePHP Js Helper - Update 3 Dropdown menus dynamically

i'm using CakePHP 2.6.1
I have a cakephp form to handle accesses with these 3 dropdown menues:
location->facility->department
I want them to be dynamic populated and so i followed this tutorial http://marnienickelson.com/2014/10/11/dynamic-dropdowns-with-cakephp-2-x/
It works well, except one little problem. If i change the "location", the "facility" Dropdown menu is filled correctly, but the "department" menu stays blank...
My AccessesController.php
public function add() {
if ($this->request->is('post')) {
$this->Access->create();
if ($this->Access->save($this->request->data)) {
$this->Session->setFlash(__('The access has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The access could not be saved. Please, try again.'));
}
}
$titles = $this->Access->Title->find('list');
$locations = $this->Access->Facility->Location->find('list');
$systems = $this->Access->System->find('list');
$this->set(compact('titles', 'locations', 'facilities', 'departments', 'systems'));
}
My get_by_location.ctp (and i have an equal file called get_by_facility.ctp)
<?php foreach ($facilities as $key => $value): ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php endforeach; ?>
And at the end of my add.ctp
<?php
$this->Js->get('#AccessLocationId')->event('change',
$this->Js->request(array(
'controller'=>'facilities',
'action'=>'getByLocation'
), array(
'update'=>'#AccessFacilityId',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
$this->Js->get('#AccessFacilityId')->event('change',
$this->Js->request(array(
'controller'=>'departments',
'action'=>'getByFacility'
), array(
'update'=>'#AccessDepartmentId',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
?>
I know the second event'change' isnt recognized and thats why my 3rd dropdown stays blank... Is there an other event then 'change'? Or could i put these two ajax requests in one?
This Blog helped me alot Euromarks blog
I just changed my get_by_location.ctp file:
<?php
if (!empty($facilities)) {
echo '<option value="">' . __('pleaseSelect') . '</option>';
foreach ($facilities as $k => $v) {
echo '<option value="' . $k . '">' . h($v) . '</option>';
}
} else {
echo '<option value="0">' . __('noOptionAvailable') . '</option>';
}
So if first dropdown is changed, the second one will display "please select".

Laravel. Controller not getting the values from the Form

The controller is not getting the data from the FORM. I realise that the Form has by default a Post method, while the Route is using a Get, but if I change that, then the form will not display the form fields. Validation fails as the "required" does not get any values, so it returns to the same page. If I remove the validation filter, then it does go to the results page, but all it does is show ALL of the content of the table, since it is getting no parameters (where) from the Form. The weird thing is that in the past, it worked, but I must have messed up with some part of the code and now it doesn't. To save space here I have left out many fields which dont play a role in the problem.
The Form has three interdependent Fields Country, Region and Town, which are filled up alright.
FORM:
<form action = "{{URL::route('sacapropiedades')}} "class="form-horizontal" id="my_form" name="my_form">
<div class="form-group">
<div class="col-sm-3">
<label for="country">Pays</label>
<select name ="country" {{ (Input::old('country')) ?' value ="' . e(Input::old('country')). '"' : '' }} id = "country" class="form-control">
#foreach($countries as $country)
<option value="{{$country->country}}">{{$country->country}}</option>
#endforeach
</select>
</div>
<div class="col-sm-3">
<label for="town">Ville</label>
<select name ="town" {{ (Input::old('town')) ?' value ="' . e(Input::old('town')). '"' : '' }}id = "town" class="form-control">
</select>
</div>
</div><!-- END OF THIRD FORMGROUP -->
<div class="form-group">
<div class="col-sm-4">
</div>
<div class="col-sm-2">
<button type="submit" class="btn btn-success">Enviar</button>
<button type="reset" class="btn btn-danger">Borrar</button>
</div>
</div>
</form>
ROUTES
Route::get('realestate/listproperty', array(
'as' =>'sacapropiedades',
'uses' =>'countriesregionstownsController#findproperty'
));
CONTROLLER
public function findproperty(){
/*IT REPEATS THE COUNTRY QUERY ABOVE BECAUSE IT IS GOING TO USE IT
*ON THE RESULTS PAGE AND IT GIVES THE USER TO SELECT AGAIN OTHER COUNTRIES
*WITHOUT HAVING TO RETURN TO THE FIRST PAST PAGE*/
$countries = DB::table('properties')
->select('country')
->distinct()
->get();
/*FIRST VALIDATE INPUT DATA*/
$validator = Validator::make(Input::all(),
array(
'country' =>'required',
'regions' =>'required',
'transaction' =>'required',
'town' =>'required'
));
if($validator->fails()){
return Redirect::route('showrealestate')
->withErrors($validator)
->withInput();
}
else{
$country = Input::get('country');
$region = Input::get('regions');
$town = Input::get('town');
$transaction = Input::get('transaction');
$pricefrom = Input::get('pricefrom');
$priceto = Input::get('priceto');
$roomsfrom = Input::get('roomsfrom');
$roomsto = Input::get('roomsto');
$builtyear = Input::get('builtyear');
$swimming = Input::get('swimming');
$garden = Input::get('garden');
$garage = Input::get('garage');
$message = Input::get('message');
}
$country = DB::table('countries')->where('id_pais', $country)->pluck('nombre_pais');
$region = DB::table('regions')->where('id_region', $region)->pluck('nombre_region');
$town = DB::table('cities')->where('id_localidad', $town)->pluck('nombre_localidad');
$users = DB::table('users')
->join('properties', 'users.id', '=', 'properties.id_user_fk')
->select('users.email', 'properties.id_user_fk', 'properties.country', 'properties.region', 'properties.town',
'properties.price', 'properties.rooms','properties.m2','properties.swimming',
'properties.garden','properties.garage','properties.builtyear','properties.message',
'properties.pic1',
'properties.pic2', 'properties.pic3','properties.pic4','properties.pic5','properties.pic6');
if (!empty($country)) {
$users = $users->where('country', '=', $country);
}
if (!empty($region)) {
$users = $users->where('region', '=', $region);
}
if (!empty($town)) {
$users = $users->where('town', '=', $town);
}
if (!empty($transaction)) {
$users = $users->where('transaction', '=', $transaction);
}
if (!empty($pricefrom)) {
$users = $users->where('price', '>', $pricefrom);
}
if (!empty($priceto)) {
$users = $users->where('price', '<', $priceto);
}
if (!empty($roomsfrom)) {
$users = $users->where('rooms', '>', $roomsfrom);
}
if (!empty($roomsto)) {
$users = $users->where('rooms', '<', $roomsto);
}
if (!empty($builtyear)) {
$users = $users->where('builtyear', '>', $builtyear);
}
if (!empty($swimming)) {
$users = $users->where('swimming', '=', $swimming);
}
if (!empty($garage)) {
$users = $users->where('garage', '=', $garage);
}
if (!empty($garden)) {
$users = $users->where('garden', '=', $garden);
}
if (!empty($message)) {
$users = $users->where('message', '=', $message);
}
$users = $users->get();
return View::make('realestate.externa.listproperty', compact('users','countries'));
}
A post method is mandatory, otherwise Laravel will not redirect it to the correct method with the correct data. How was it working before? By luck, probably. :)
Route::get('realestate/listproperty', array(
'as' =>'sacapropiedades',
'uses' =>'countriesregionstownsController#findproperty'
));
Route::post('realestate/listproperty', array(
'as' =>'sacapropiedades',
'uses' =>'countriesregionstownsController#findproperty'
));
or
Route::match(array('GET', 'POST'), 'realestate/listproperty', array(
'as' =>'sacapropiedades',
'uses' =>'countriesregionstownsController#findproperty'
));
or
Route::any('realestate/listproperty', array(
'as' =>'sacapropiedades',
'uses' =>'countriesregionstownsController#findproperty'
));
Then you'll probably need to not validate on GET:
if (Request::getMethod() == 'POST')
{
$validator = Validator::...
}
EDIT:
Sorry I overlooked this problem:
Instead of writing your FORM tag manually, use Laravel's FormBuilder class:
<?php Form::open(array('route' => 'sacapropiedades', 'class' => 'form-horizontal', 'id' => 'my_form', 'name' => 'my_form')); ?>
The difference is that it will add the method for you and it will also add a csrf token to your form.

Resources