WP_Query() 'orderby' => 'title' not working - sql-order-by

So I have this query
$args = array(
'post_type' => 'course', // custom post type
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title'
);
$courses = new WP_Query($args);
This gives me what I want, but the orderby statement is being ignored. When I dump the $courses->request I get this
'SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type
= 'course' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.menu_order ASC '
It is defaulting the orderby to menu_order instead of title. What's going on here?

I was facing the same issue and I solved it using 'post_title' instead of 'title'.
$args = array(
'post_type' => 'course', // custom post type
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'post_title' // change here
);
$courses = new WP_Query($args);

check whether you have used parse_query or pre_get_posts
hook somewhere in the website
add_action( 'pre_get_posts', 'function_name' );
add_filter( 'parse_query', 'function_name' );

Related

WordPress post pagination not working with ajax

I am trying to load my WordPress posts using ajax. I implemented the following functions to do the pagination for me.
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$the_query = new WP_Query(
array(
'posts_per_page' => 6,
'post_type' => 'post',
'paged' => $paged
)
);
<?php next_posts_link( 'Next →', $the_query ->max_num_pages); ?>
<?php previous_posts_link( 'Previous ← ' ); wp_reset_query();?>
When I try to navigate through the paginated link (Next/Previous), the URL is looking like this:
http://localhost/vendor/wp-admin/admin-ajax.php?paged=2
The URL i am trying to get:
http://localhost/vendor/vendorpage/page/2/
Is there any way to help me out?
Try the below code -
ob_start(); // Turn output buffering on
global $paged;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 6,
'paged' => $paged,
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) {
while ($the_query->have_posts()) {
$the_query->the_post();
//your code
}
$big = 999999999;
echo paginate_links(
array(
'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
'format' => '?paged=%#%',
'current' => max(
1,
get_query_var('paged')
),
'total' => $the_query->max_num_pages //$q is your custom query
)
);
}
return ob_get_clean();
wp_reset_query();

Fetch products if image is found in woocommerce and filter the products

I have a big problem, I used this code in my website - fetch products if image is found in woocommerce?
<?php
$args = array(
'post_type' => 'product',
'stock' => 1,
'posts_per_page' => 9,
'orderby' =>'date',
'orderby' => 'rand',
'meta_query'=>array(
array(
'key'=>'_thumbnail_id',
'compare' => 'EXISTS'
)
)
);
$loop = new WP_Query( $args );
while ($loop->have_posts()) : $loop->the_post();
echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog');
endwhile;
?>
But I can't filter the products, do I have to put some variable in orderby?
I can't put this in order

Sorting in CakePHP with custom routes

I was trying to find a solution on-line (as always) but came up with nothing obviously.
I'm using CakePHP and I need to add some sorting into some controllers. I would also like to create custom routes for that. So here's my code that is not working (pagination works, sorting nope):
RatesController.php:
public $paginate = array(
'Rate' => array(
'limit' => 10,
'order' => array(
'Rate.created' => 'desc'
),
'conditions' => array( 'Rate.accepted' => 1 ),
//'fields' => array('Rate.*', 'User.username')
),
'Airline' => array(
'limit' => 50,
/*'order' => array(
'Airline.rate' => 'desc',
'Airline.name' => 'asc'
),*/
'conditions' => array(
'Airline.rate >' => 0
),
'fields' => array('Airline.id', 'Airline.name', 'Airline.image_id', 'Airline.rate', 'Image.*')
)
);
function index($category = 'airlines'){
pr($this->request);
$data = $this->paginate('Airline');
pr($data);
}
And in view:
$this->Paginator->options(array(
'url' => array(
'controller' => 'rates',
'action' => 'index',
'category' => $category
)
));
echo $this->Paginator->first('«', array('escape' => false), null, array('class' => 'disabled', 'escape' => false));
echo $this->Paginator->prev('<', array('escape' => false), null, array('class' => 'disabled', 'escape' => false));
echo $this->Paginator->numbers(array(
'modulus' => 6,
'separator' => false
));
echo $this->Paginator->next('>', array('escape' => false), null, array('class' => 'disabled', 'escape' => false));
echo $this->Paginator->last('»', array('escape' => false), null, array('class' => 'disabled', 'escape' => false));
echo' sort by ';
echo $this->Paginator->sort('Airline.rate');
echo' or by ';
echo $this->Paginator->sort('Airline.name');
Routes:
Router::connectNamed(array('page'), array('default' => false, 'greedy' => false));
Router::connectNamed(array('sort', 'direction'), array('default' => false, 'greedy' => false));
Router::connect('/rate-airlines', array('controller' => 'rates', 'action' => 'index', 'category' => 'airlines'));
/*
Router::connect(
'/rate-airlines/:page/',
array('controller' => 'rates', 'action' => 'index', 'category' => 'airlines'),
array(
'named' => array('page' => '[a-z]+')
)
);
Router::connect(
'/rate-airlines/:page/:sort/:direction',
array('controller' => 'rates', 'action' => 'index', 'category' => 'airlines'),
array(
'pass' => array('page', 'sort', 'direction'),
//'id' => '[0-9]+',
'named' => array('page' => '[\d]+', 'sort', 'direction')
)
);*/
Router::connect(
'/rate-airlines/:sort/:direction',
array('controller' => 'rates', 'action' => 'index', 'category' => 'airlines'),
array(
'named' => array('sort', 'direction')
)
);
I seriously have no idea why it's not working, I've already spent hours trying to make it work, seeking answers.
Ps. No matter what I did I couldn't manage to put :sort and :direction into named array in request:
CakeRequest Object
(
[params] => Array
(
[plugin] =>
[controller] => rates
[action] => index
[named] => Array
(
)
[pass] => Array
(
)
[sort] => Airline.rate
[direction] => asc
[category] => airlines
[isAjax] =>
)
...
)
Any ideas please?
Mike
You really shouldn’t use route parameters for sorting. It was such a bad idea that CakePHP have dropped them in the forth-coming 3.x release.
Instead, use query string parameters. That’s exactly what they’re for: manipulating a single view. If you have a list, pass parameters like ‘sort’ and ‘direction’ there.
Say you have a URL like http://example.com/rates/?sort=name&direction=asc, you can then parse it in your controller as follows:
<?php
class RatesController extends AppController {
public function index() {
$sort = isset($this->request->query['sort']) ? $this->request->query['sort'] : 'created';
$direction = isset($this->request->query['direction']) ? $this->request->query['direction'] : 'desc';
$this->Paginator->settings = array(
'order' => array($sort => $direction)
);
$rates = $this->paginate('Rate');
$this->set(compact('rates'));
}
}
I also like to go one step further and use query strings for pagination…
<?php
class AppController extends Controller {
public $paginate = array(
'paramType' => 'querystring'
);
}
…But that’s just personal preference.
The above was written during a long day. After thinking about it, CakePHP handles sorting in pagination out of the box. You don’t need to manually specify routes containing the name parameters.
So long as you use the Pagination component and Paginator helper (as you have done), and defined a single route for your controller action, you don’t need to do anything else. In your case, your controller would look like:
<?php
class RatesController extends AppController {
public function index() {
$rates = $this->paginate('Rate');
$this->set(compact('rates'));
}
}
And your view would look like:
<?php echo $this->Paginator->sort('Airline.name'); ?>
If you wanted to rewrite /rates to /rates-airlines, then your single route would look like this:
<?php
Router::connect('/rates-airlines', array(
'controller' => 'rates',
'action' => 'index',
));
With the above, the paginate call will take into account the column to sort by and the direction.
Sorry for the convoluted answer above!
thanks for your replies. The thing is that I really need custom routing for pagination, so I finally managed to achieve what I wanted using following code:
In AppController.php (note that all $this->request->query[...] variables were added just because I also wanted to use sorting interface via forms with GET method)
function beforeFilter() {
if (isset($this->request->params['page'])) {
$this->request->params['named']['page'] = $this->request->params['page'];
}elseif( isset($this->request->query['page']) ){
$this->request->params['named']['page'] = $this->request->query['page'];
}
if (isset($this->request->params['sort'])) {
$this->request->params['named']['sort'] = $this->request->params['sort'];
}elseif (isset($this->request->query['sort'])) {
$this->request->params['named']['sort'] = $this->request->query['sort'];
}
if (isset($this->request->params['direction'])) {
$this->request->params['named']['direction'] = $this->request->params['direction'];
}elseif (isset($this->request->query['direction'])) {
$this->request->params['named']['direction'] = $this->request->query['direction'];
}
in routes.php
Router::connect('/rates-airlines', array('controller' => 'rates', 'action' => 'index', 'airlines'));
Router::connect(
'/rates-airlines/:page',
array('controller' => 'rates', 'action' => 'index', 'airlines'),
array(
'named' => array('page' => '[\d]+')
)
);
Router::connect(
'/rates-airlines/:page/:sort/:direction',
array('controller' => 'rates', 'action' => 'index', 'airlines'),
array(
'named' => array('page' => '[\d]+', 'sort', 'direction')
)
);
Router::connect(
'/rates-airlines/:sort/:direction',
array('controller' => 'rates', 'action' => 'index', 'airlines'),
array(
'named' => array('sort', 'direction')
)
);
Hope someone will find this useful!
Mike
There is an easier way. Just add one more route with '/*':
Router::connect('/rates-airlines', array('controller' => 'rates', 'action' => 'index', 'airlines'));
Router::connect('/rates-airlines/*', array('controller' => 'rates', 'action' => 'index', 'airlines'));
And all will work correctly.

Integrate Multi-Channel Sales With Magento API

Looking for advice on the sequence of Magento API calls necessary to implement this business process:
An inventory item (either physical or virtual/digital) is made available by the seller via an external channel (not the regular web storefront).
A customer initiates a payment directly to me without going through the Magento cart / checkout flow (can I lookup sales tax at this point?)
After the payment has been made, I want to trigger Magento post-processing logic to record the sale, manage inventory, etc.
For physical goods, I want to trigger Magento fulfillment logic to occur to create the shipment, etc.
I'm aware of the SOAP API, I'm looking for help to understand which actions need to be taken along the way to enact this process.
Here is very basic example how Magento API can be used for your case:
Connect to Magento via API
$user = 'apiUser'; $password = 'apiKey';
$proxy = new SoapClient('http://your_magento_host.com/api/v2_soap/?wsdl');
$sessionId = $proxy->login($user, $password);
Create or select customer
// Create customer
$customerList = $proxy->customerCustomerCreate($sessionId, array( 'email' => 'customer#gmail.com', 'firstname' => 'Will', 'lastname' => 'Smith', 'password' => 'qwerty', 'website_id' => 1, 'store_id' => 1, 'group_id' => 1 ));
$customer = (array) $customerList[0];
$customer['mode'] = 'customer';
// Or select existing customer (by email)
$filter = array(
'complex_filter' => array(
array(
'key' => 'email',
'value' => array('key' => 'in', 'value' => 'customer#gmail.com')
)
) );
$customerList = $proxy->customerCustomerList($sessionId, $filter);
$customer = (array) $customerList[0];
$customer['mode'] = 'customer';
Create cart
$cartId = $proxy->shoppingCartCreate($sessionId, 1);
$proxy->shoppingCartCustomerSet($sessionId, $cartId, $customer);
Select product (by sku)
$filter = array(
'complex_filter' => array(
array(
'key' => 'sku',
'value' => array('key' => 'in', 'value' => 'T-SHIRT001')
)
) );
$productList = $proxy->catalogProductList($sessionId, $filter);
$product = (array) $productList[0];
$product['qty'] = 1;
Add product to cart
$proxy->shoppingCartProductAdd($sessionId, $cartId, array($product));
Set billing/shipping address. You should add this addresses to customer if you just create it before.
$address = array(
array(
'mode' => 'shipping',
'firstname' => $customer['firstname'],
'lastname' => $customer['lastname'],
'street' => 'street address',
'city' => 'city',
'region' => 'region',
'telephone' => 'phone number',
'postcode' => 'postcode',
'country_id' => 'country ID',
'is_default_shipping' => 0,
'is_default_billing' => 0
),
array(
'mode' => 'billing',
'firstname' => $customer['firstname'],
'lastname' => $customer['lastname'],
'street' => 'street address',
'city' => 'city',
'region' => 'region',
'telephone' => 'phone number',
'postcode' => 'postcode',
'country_id' => 'country ID',
'is_default_shipping' => 0,
'is_default_billing' => 0
),
);
$proxy->shoppingCartCustomerAddresses($sessionId, $cartId, $address);
Set shipping mathod
$proxy->shoppingCartShippingMethod($sessionId, $cartId, 'flatrate_flatrate');
Set payment method.
$paymentMethod = array(
'po_number' => null,
'method' => 'checkmo',
'cc_cid' => null,
'cc_owner' => null,
'cc_number' => null,
'cc_type' => null,
'cc_exp_year' => null,
'cc_exp_month' => null
);
$proxy->shoppingCartPaymentMethod($sessionId, $cartId, $paymentMethod);
Place order
$orderId = $proxy->shoppingCartOrder($sessionId, $cartId, null, null);
Now check Sales->Orders in Magento admin area and you'll see new order.
More details here: http://www.magentocommerce.com/api/soap/introduction.html
Yes, you can catch information about Tax:
1) Without order saving. Step 9:
$result = $proxy->shoppingCartTotals($sessionId, $cartId);<br>
var_dump($result);
You'll see array of subtotal, taxes, discounts and total.
2) With order saving. Step 10:
$result = $proxy->salesOrderInfo($sessionId, $orderId);<br>
var_dump($result);
// cancel order<br>
$result = $proxy->salesOrderCancel($sessionId, $orderId);
More information about used API calls here:
http://www.magentocommerce.com/api/soap/checkout/cart/cart.totals.html
http://www.magentocommerce.com/api/soap/sales/salesOrder/sales_order.info.html
http://www.magentocommerce.com/api/soap/sales/salesOrder/sales_order.cancel.html

CdbCriteria BELONG_TO

I have a model (Inmueble) with this relation:
'direccion' => array(self::BELONGS_TO, 'Direccion', 'direccion_id_direccion'),
In this example:
$criteria=new CDbCriteria;
$criteria->addCondition('name = ' .$name,'AND');
$listInmueble=new CActiveDataProvider('Inmueble',
array('criteria' => $criteria,
'pagination' => array('pageSize' => 10),
));
I accesing in the condition to the attribute name of the model Inmueble.
How can i do a CdbCriteria accesing the attributes of the relation, for example where direccion.city = 'something'?
Thanks!
try this
$criteria->with = array(
'direccion' => array(
'condition' => 'direccion.city = :something',
'params' => array(
':something' => 'someValue'
)
)
);

Resources