I am having a problem getting a custom query to alphabetize. It keeps defaulting to displaying in the order of the date it was posted. Below is my php function.
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for each of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','machinery');
$statesAll = array('SC','TX','WA');
// set $statusArray dependent on whether or not "all" is selected in the dropdown menu
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
<li>
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
?>
This above function is called by the ajax function that follows:
function do_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
Is there something simple that I'm missing here? I have a similar custom query on the page when it loads (although that initial load query doesn't have the select menu values as args), and they display in alphabetical order just fine. It's only after the ajax call to filter the list that they are no longer in order.
I have found the issue after googling the problem for quite a while. I read that some of the people who were having this problem found that their theme was using a plugin called Post Types Order. It overrides the ability to set the orderby arg.
I looked at the plugins, and sure enough, Post Types Order was there. Everything I read said that the problem could be solved by unchecking "auto sort" in the settings for the plugin. However, I did that, and orderby still didn't work. I had to completely deactivate the plugin to get orderby title to work.
Related
I'm using jQueryUI AutoComplete with WordPress to fetch terms of a custom taxonomy as a user types in a search box.
I have a lot of sports brands as custom taxonomy terms, so, for example, the term Adidas can have many subterms. Now when I type a, it displays...
Adidas
Adidas Shoes
Adidas Socks
etc...
...causing the other brands to get in the dark. So, when I type a, I would like the results to show as follows...
Adidas
Amphipod
Asics
etc...
...until I continue typing ad, and only then should the Adidas results with the subterms appear, like in the first example. Is this possible to accomplish? Is jQueryUI AutoComplete able to order the results for me like this, or do I need to sort them on the server side with a PHP function like sort, usort etc.? I've tried to write a few different PHP sort functions to no avail so far, but I really have no idea right now.
This is the code I have right now:
autocomplete.js
$(function() {
var url = MyAutocomplete.url + "?action=my_search";
$('.search-field').autocomplete({
source: url,
delay: 500,
minLength: 2,
sortResults: true
})
});
functions.php (WordPress)
function my_search()
{
$args = array(
'search' => strtolower($_GET['term']),
'taxonomy' => array('suggestion_string'),
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'number' => 10,
);
$search_query = new WP_Term_Query($args);
$results = array( );
if ( $search_query->get_terms() ) {
foreach($search_query->get_terms() as $term) {
$results[] = array(
'label' => $term->name,
);
}
}
else {
}
// Tried to write a few different sort functions here to no avail, like:
sort($results);
$data = json_encode($results);
echo html_entity_decode( $data );
exit();
}
add_action( 'wp_ajax_my_search', 'my_search' );
add_action( 'wp_ajax_nopriv_my_search', 'my_search' );
Everything is possible my friend you just have to code it as you wish. You can achieve what you want on the server side as well as on the client side, in this case I would recommend the server side though.
If you do not want autocomplete show subcategories just do not deliver those. Either you eliminate names starting with the same word first or you exclude subcategories. Here is my code for you for the first possibility:
function my_search()
{
$args = array(
'search' => strtolower($_GET['term']),
'taxonomy' => array('suggestion_string'),
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'number' => 10,
);
$search_query = new WP_Term_Query($args);
$results = array( );
if ( $search_query->get_terms() ) {
foreach($search_query->get_terms() as $term) {
$results[] = array(
'label' => $term->name,
);
}
}
else {
}
$filtered = [];
$existing = [];
if(strlen($_GET['term'])<2) {
foreach($results as $term) {
$first_word = explode(" ",$term["label"])[0];
if(!in_array($first_word,$existing) {
array_push($existing,$first_word);
$filtered[] = $term;
}
}
} else {
$filtered = $results;
}
$data = json_encode($results);
echo html_entity_decode( $data );
exit();
}
add_action( 'wp_ajax_my_search', 'my_search' );
add_action( 'wp_ajax_nopriv_my_search', 'my_search' );
I'm designing a website for a local performing arts venue, and I would like to add some code so that specific event posts on the "Events" page will automatically be moved from "Events" to a different "Past Performances" page after the date of the event has passed. I've looked around for any existing solution to this query and haven't yet found one.
Create a child theme or add page-events.php and page-past-performances.php, you may copy/paste your current theme page.php code.
Here you may choose 2 options:
Create a special loop for each template. For page-events.php:
<?php
$today = getdate();
$args = array('date_query' => array(
array(
'after' => array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
'inclusive' => true
)
));
$query = WP_Query($args);
//Here goes the loop
For page-past-performances.php:
<?php
$today = getdate();
$args = array('date_query' => array(
array(
'before' => array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
inclusive => false
)
));
$query = WP_Query($args);
//Here goes the loop
The second option uses the action hook pre_get_posts, it could look something like this (inside your functions.php file):
<?php
add_action('pre_get_posts', 'date_filter');
function date_filter($query) {
if($query->pagename == 'events') {
$query->set('date_query', [[
'after' => //same as above
'inclusive' => true
]]);
}
if($query->pagename == 'past-performances') {
$query->set('date_query', [[
'before' => //same as above
'inclusive' => false
]]);
}
}
?>
I'm newbie with Yii.
I have a CGridview with a cutom dataprovider which takes a parameter $select:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'beneficiary-grid',
'dataProvider' => $model->searchForVoucherAssignment($select),
'filter' => $model,
'columns' => array(
'id',
'registration_code',
'ar_name',
'en_name',
'family_member',
'main_income_source',
'combine_household',
array( 'class'=>'CCheckBoxColumn', 'value'=>'$data->id', 'selectableRows'=> '2', 'header' => 'check',
),
),
));
That parameter $select takes its values from dropdownlist:
$data = CHtml::listData(Distribution::model()->findAll(array("condition"=>"status_id = 2")), 'id', 'code');
$select = key($data);
echo CHtml::dropDownList(
'distribution_id',
$select, // selected item from the $data
$data,
array(
)
);
So I defined a script to update the CGridview depending on the value of dropdownlist
Yii::app()->clientScript->registerScript('sel_status', "
$('#selStatus').change(function() {
$.fn.yiiGridView.update('beneficiary-grid', {
data: $(this).serialize()
});
return false;
});
");
My model:
public function searchForVoucherAssignment ($distribution_id = 0) {
$criteria = new CDbCriteria;
if ($distribution_id != 0) {
$criteria->condition = "Custom Query...!!";
}
$criteria->compare('id', $this->id);
//Custom Criteria
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => 20,
),
));
}
The problem is that the CGridview isn't changing where a value of the dropdownlist changed...
I think you have selected the wrong Id for the change event. The Id should be
$('#distribution_id').change(function() {
I am trying to get the IDs of all the selected check boxes in yii using JAVASCRIPT. Now i am able to get only the first element ID. Can anyone please suggest the correct code to get all the check box ID.
My View:
<input type="button" value="Multiple Host Date Entries" onclick="act();" />
<div id="grid"></div>
<?php
//zii.widgets.grid.CGridView bootstrap.widgets.TbExtendedGridView
$obj=$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id'=>'host_grid',
'dataProvider'=>$dataProvider,
'type' => 'striped bordered',
//'filter' => $model,
//'type' => 'striped bordered condensed',
//'summaryText' => false,
////'afterAjaxUpdate'=>'\'changeTRColor()\'',
//'itemView'=>'_view',
'columns'=>array(
array(
'id' => 'selectedIds',
'class' => 'CCheckBoxColumn',
'selectableRows'=>2,
'value' => '$data->host_id',
'checkBoxHtmlOptions' => array('name' => 'idList[]'),
),
array( // display 'create_time' using an expression
'name'=>'host_name',
'value'=>'$data->host_name',
),
array(
'name'=>'host_serviceid',
'value'=>'$data->host_serviceid',
),
array(
'name'=>'status',
'value'=>'$data->status',
),
array(
'class'=>'CButtonColumn',
'template'=>'{edit_date}{update}{delete}',
'htmlOptions'=>array('width'=>'95px'),
'buttons' => array(
'update'=> array(
'label' => 'Update',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/a.png',
),
'delete'=> array(
'label' => 'Delete',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/d.png',
),
'edit_date' => array( //the name {reply} must be same
'label' => 'Add Date', // text label of the button
'url' => 'Yii::app()->createAbsoluteUrl("NimsoftHostsDetails/View", array("id"=>$data->host_id))', //Your URL According to your wish
'imageUrl' => Yii::app()->baseUrl.'/images/icons/m.png', // image URL of the button. If not set or false, a text link is used, The image must be 16X16 pixels
),
),)
),
))
;
?>
I must select some check boxes and click on multiple host date entries button to go to the specific controller.
My JavaScript:
function act()
{
var idList=$("input[type=checkbox]:checked").serializeArray();
var jsonStr = JSON.stringify(idList);
/* Object.keys(idList).forEach(function(key) {
console.log(key, idList[key]);
alert(idList[key]);
});*/
var a=$("input[type=checkbox]:checked").val();
alert(a);
if(idList!="")
{
if(confirm("Add Dates for multiple hosts?"))
{
var url='<?php echo $this->createUrl('Nimsoft/Date_all',array('idList'=>'val_idList')); ?>';
url=url.replace('val_idList',jsonStr);
//url=url.replace('val_idList',json_encode(idList));
//alert(url);
window.open(url);
/*$.post('Date_all',idList,function(response)
{
$.fn.yiiGridView.update("host_grid");
});*/
}
}
else
{
alert("Please Select atleast one host");
}
}
I need to pass the IDs to NIMSOFT controller so that I can have a for loop to process each one of those.
you can retrieve the checked column in client side (javasctipt):
var idArray = $(gridID).yiiGridView('getChecked', columnID);
// or
$.fn.yiiGridView.getSelection(gridID);
For all checked row ids we use this
var id = $.fn.yiiGridView.getChecked("your-grid-id", "selectedIds"); // array of seleted id's from grid
Am using Yii and Activehighcharts to show charts.
http://www.yiiframework.com/extension/activehighcharts
controller is as follows
public function actionChartView(){
$dataProvider=new CActiveDataProvider('ChartData',array(
'criteria'=>array(
'condition'=>'dID=2',
'order'=>'time ASC',
),
'pagination'=>array(
'pageSize'=>50,
),
)
);
$p=$dataProvider->pagination;
$p->setItemCount($dataProvider->getTotalItemCount());
$p->currentPage=$p->pageCount-1;
if(isset($_GET['json']) && $_GET['json'] == 1){
$count = ChartData::model()->count();
for($i=1; $i<=$count; $i++){
$data = ChartData::model()->findByPk($i);
$data->data += rand(-10,10);
$data->save();
}
echo CJSON::encode($dataProvider->getData());
}
else{
$this->render('ChartView',array('dataProvider'=>$dataProvider,));
}
}
View as
$this->Widget('ext.ActiveHighcharts.HighchartsWidget', array(
'dataProvider'=>$dataProvider,
'template'=>'{items}',
'id'=>'Temperature',
'options'=> array(
'title'=>array(
'text'=>'Temperature'
),
'chart'=>array(
"zoomType"=>'x',
),
'xAxis'=>array(
'title' => array('text' => 'Time',),
'categories' => 'time',
'labels' => array(
'rotation' => -90,
'y' => 20,
),
),
'yAxis'=>array(
'title' => array('text' => 'DegC'),
),
'series'=>array(
array(
'type'=>'areaspline',
'name'=>'Temperature', //title of data
'dataResource'=>'data', //data resource according to datebase column
)
),
)
));
i need to update the chart in every 2 minutes with ajax.
also i need to get old data.
how to handle these scenarios.
in your ajax call success call back update the data in the chart using the api methods provided in highcharts documentation.
please refer this link it will help you to find a good solution.
Ok. To best answer your question i will try to clear things as much as possible.
First you need to create a view (a php file that will contain your highchart code)
Second you need to edit your Controller (let's assume siteController) and create an action to call the view you've just create. Inside that action you will need to connect and query the database.
See the below sample code:
siteController action:
public function actionAtencionesMensuales() {
$sql = Yii::app()->db->createCommand('
SELECT DISTINCT MONTH(hora) as mes, count(*) as total
FROM visitas
WHERE YEAR(hora)=YEAR(CURDATE())
GROUP BY MONTH(hora)')->queryAll();
$mes = array();
$total = array();
for ($i = 0; $i < sizeof($sql); $i++) {
$mes[] = $sql[$i]["mes"];
$total[] = (int) $sql[$i]["total"];
}
$this->render('my_view', array('mes' => $mes, 'total' => $total));
}
}
In the View:
<?php
$this->Widget('ext.highcharts.HighchartsWidget', array(
'options' => array(
'exporting' => array('enabled' => true),
'title' => array('text' => 'Mes'),
'theme' => 'grid',
'rangeSelector' => array('selected' => 1),
'xAxis' => array(
'categories' => $mes
),
'yAxis' => array(
'title' => array('text' => 'Cantidad')
),
'series' => array(
array('name' => 'Total', 'data' => $total = array_map('intVal', $total)),
)
)
));
?>
Within the series of the chart, it's better to use when calling the variable:
$total = array_map('intVal', $total)
Instead of just:
$total
Good luck :)