Query sticky posts only in Wordpress - sticky

I have the query below to gather the sticky posts. This works when i actually have sticky posts, but when i have no sticky posts it just queries 10 (none sticky) posts. How can i adjust the query to gather just and only sticky posts and if none are found, just do nothing. Thanks
/* Get all sticky posts */
$sticky = get_option( 'sticky_posts' );
/* Sort the stickies with the newest ones at the top */
rsort( $sticky );
/* Get the 5 newest stickies (change 5 for a different number) */
$sticky = array_slice( $sticky, 0, 5 );
/* Query sticky posts */
$the_query2 = new WP_Query( array( 'ignore_sticky_posts' => 'false', 'post__in' => $sticky, 'post_type' => 'ad_listing' ) );
echo $the_query2->post_count;

Found out that by adding this if statement, only sticky posts are queried!
/* Get all sticky posts */
$sticky = get_option( 'sticky_posts' );
if (!empty($sticky)) {
//Do the query etc.
}

Related

Getting WooCommerce customers and/or orders by emailaddress with REST API v3

I have read through tons of related questions and answers, but I'm not getting my desired results.
Not sure if API v3 even handles these simple filters for customers and orders.
What I want to do is filter orders by email and/or zipcode so people can lookup their orders from our Apps.
/*
* Get Customer
* email#example.com
*/
$data = [
'filter' => [
'email' => '****#gmail.com',
//'billing_phone' => '123156466'
]];
print_r($woocommerce->get('customers', $data));
/*
* Get Orders
* email#example.com
*/
$data = [
'filter' => [
//'fields' => 'id,status,email',
'email' => '****#gmail.com'
]
];
print_r($woocommerce->get('orders', $data));
Also tried to append a querystring, like:
$qs = http_build_query($data);
print_r($woocommerce->get('orders/?' . $qs));
Also tried without 'filter', so no nested arrray.
Am I trying to make things work that are not supported?

TYPO3 Extension - Redirect to another page in show action if no record is set or not available

How can I redirect to another page when someone access the detail page but without a record or if record is not available?
I have detail records like
domain.com/abc/ABC1234
When somone enters
domain.com/abc/
... I get:
Uncaught TYPO3 Exception
#1298012500: Required argument "record" is not set for Vendor\Extension\Controller\ActionController->show. (More information)
TYPO3\CMS\Extbase\Mvc\Controller\Exception\RequiredArgumentMissingException thrown in file
/is/htdocs/www/typo3_src-8.7.11/typo3/sysext/extbase/Classes/Mvc/Controller/AbstractController.php in line 425.
... in this case I want it to redirect to:
domain.com/other-page/
... I also need it if a specific record is not available.
... how to do so?
/**
* action show
*
* #param \Action $record
* #return void
*/
public function showAction(Action $record) {
$this->view->assign('record', $record);
}
Here are some examples TYPO3 Extbase - redirect to pid ... but not sure how to implement it
Edit: What works is ...
/**
* action show
*
* #param \Action $record
* #return void
*/
public function showAction(Action $record=null) {
if ($record === null) {
$pageUid = 75;
$uriBuilder = $this->uriBuilder;
$uri = $uriBuilder
->setTargetPageUid($pageUid)
->build();
$this->redirectToUri($uri, 0, 404);
} else {
$this->view->assign('record', $record);
}
}
The redirect method needs an action and controller parameter. So your redirect code is wrong.
$this->redirect($actionName, $controllerName = NULL, $extensionName = NULL, array $arguments = NULL, $pageUid = NULL, $delay = 0, $statusCode = 303);
To redirect to an PageUID you need to use the uriBuilder and the redirectToUri method. See here for an example.
This should do the trick:
public function showAction(Action $record=null) {
if ($record === null) {
$this->redirect(/* add parameters as needed */);
} else {
// other code
}
Alternative Solution (from Simon Oberländer)
public function intializeShowAction() {
if (!$this->request->hasArgument('record')) {
$this->redirect(/* add parameters as needed */); // stops further execution
}
}
Your question suggests that there should be an other action without arguments, probably a listAction, that is the DEFAULT action. The default action gets called when no action is specified. It is the first action enlisted in the ExtensionUtility::configurePlugin() call.
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'Vendor.' . $_EXTKEY,
'Pluginname',
array(
'Domainobject' => 'list, show',
),
// non-cacheable actions
array(
'Domainobject' => 'list, show',
)
);
Regarding > The identity property "TTTT" is no UID
You have to distinguish between no parameter and an invalid parameter. For the latter you can add #ignorevalidation to the showAction comments and do your validation testing within the action - or you can leave it to extbase that displays the error message you have seen.
Where would you get a link like domain.com/abc/TTTT/ from anyhow? Unless the link is expired.
BTW: in a production system you would disable the display of exceptions, thus the display of the website would work.
This could be a solution:
```
/**
* Show a booking object
*
* #return void
* #throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException
*/
public function showAction()
{
$bookingObject = null;
$bookingObjectUid = 0;
if ($this->request->hasArgument('bookingObject')) {
$bookingObjectUid = (int)$this->request->getArgument('bookingObject');
}
if ($bookingObjectUid > 0) {
$bookingObject = $this->bookingObjectRepository->findByIdentifier($bookingObjectUid);
}
if (!($bookingObject instanceof BookingObject)) {
$messageBody = 'Booking object can\'t be displayed.';
$messageTitle = 'Error';
$this->addFlashMessage($messageBody, $messageTitle, AbstractMessage::ERROR);
$this->redirect('list');
}
$this->view->assign('bookingObject', $bookingObject);
}
```

Query with orderings causing empty result - Extbase 6.2

I made an extbase extension and want to list my appointments ordered first by startDate and for those appointments that are on the same day I want to order them by the last name of the customer.
In my repository I made following working query:
public function findAppointmentsForList($future) {
$curtime = time();
$query = $this->createQuery();
$constraints = array();
if ($future !== NULL) {
$constraints[] = ($future) ?
$query->greaterThanOrEqual('startDate', $curtime) :
$query->lessThan('startDate', $curtime);
}
if ($constraints) {
$query->matching($query->logicalAnd($constraints));
} else {}
$orderings = array(
'startDate' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING,
// 'customer.lastName' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
);
$query->setOrderings($orderings);
return $query->execute();
}
It returns me some appointments so I assume it's working.
If I then uncomment the line 'customer.lastName... it returns 0 appointments.
What's going on? It's just the ordering, it can't possibly make the query smaller...
I don't even get any errors - I tried it with an invalid property for example and it gave me an error, so the property name is correct too.
And I debugged the working query and the last names in those customer objects where there.
This is my appointment model entry:
/**
* customer
*
* #var \vendor\extension\Domain\Model\Customer
*/
protected $customer = NULL;
And this is the TCA corresponding to it:
'customer' => array(
'exclude' => 1,
'label' => 'LLL:EXT:extension/Resources/Private/Language/locallang_db.xlf:tx_extension_domain_model_appointment.customer',
'config' => array(
'type' => 'select',
'foreign_table' => 'fe_users',
'minitems' => 0,
'maxitems' => 1,
),
),
EDIT: It's working now...but unfortunately I don't know why, changed too much in the meantime which I thought had nothing to do with this. One thing that might've affected this: startDate is of type Date and I noticed the query didn't filter it right so after I changed the curtime to new \DateTime('midnight') it was filtering correctly.
When you use related models in a query as part of the matching or orderBy then the query will be build with joins to the related tables. That means, that the result is actually smaller and will not include appointments without customers.
The strange thing is that you see the last names when you debug it, otherwise i would assume that you have some configuration errors in the TCA. Can you provide the TCA code from the apointment table and may be its model?

Security Group subpanel doesn't exist for quotes, contrats, invoices, and events modules

I am using suiteCRM 7.7.4 (Sugar Version 6.5.24) and I need to use Security group subpanel in quotes, contracts, invoices and events modules, but for some reasons I can't find it ! I did some researches and I found that this subpanel doesn't appear by default for custom modules.. some developers recommand to do not use the studio to build this kind of relationship, because simply it will not work ! for paid version of sugarCRM they say that there was a tool called "hookup tool" that creates the relationship for you... but As I am using a free version I can't use it !
Do you have any idea ?
Thank you very much !
I finaly find a solution :
Adding this few lines to "modules/AOS_Contracts/metadata/subpaneldefs.php" :
'securitygroups' => array(
'top_buttons' => array(array('widget_class' => 'SubPanelTopSelectButton', 'popup_module' => 'SecurityGroups', 'mode' => 'MultiSelect'),),
'order' => 900,
'sort_by' => 'name',
'sort_order' => 'asc',
'module' => 'SecurityGroups',
'refresh_page' => 1,
'subpanel_name' => 'default',
'get_subpanel_data' => 'SecurityGroups',
'add_subpanel_data' => 'securitygroup_id',
'title_key' => 'LBL_SECURITYGROUPS_SUBPANEL_TITLE',
),
QRR
Verifying permissions.
follow this following steps:
1. Go to Admin
2. Go to studio
3. Select your module where you want subpanel like "invoices"
4. Go to relationship
5. Add 1 to many relationship with Security group module.
6. Now repair rebuild you will find the subapnel in invoice module.
When you create 1 to many relationship with any module it will create the subpanel.
IF its not working then go for custom subpanel.
Refer this linnk I put code from same link it worked for me
This tutorial should hopefully help you to create a new subpanel under the Contacts module in Sugar using a custom link class and driven by SugarCRM 7's new SugarQuery API.
Create a new link class
This should go into custom/modules/<YourModule>/YourNewLink.php and this class will act as the custom functionality that will build your link between the two records.
<?php
/**
* Custom filtered link
*/
class YourNewLink extends Link2
{
/**
* DB
*
* #var DBManager
*/
protected $db;
public function __construct($linkName, $bean, $linkDef = false)
{
$this->focus = $bean;
$this->name = $linkName;
$this->db = DBManagerFactory::getInstance();
if (empty($linkDef)) {
$this->def = $bean->field_defs[$linkName];
} else {
$this->def = $linkDef;
}
}
/**
* Returns false if no relationship was found for this link
*
* #return bool
*/
public function loadedSuccesfully()
{
// this link always loads successfully
return true;
}
/**
* #see Link2::getRelatedModuleName()
*/
public function getRelatedModuleName()
{
return '<Your_Module>';
}
/**
*
* #see Link2::buildJoinSugarQuery()
*/
public function buildJoinSugarQuery($sugar_query, $options = array())
{
$joinParams = array('joinType' => isset($options['joinType']) ? $options['joinType'] : 'INNER');
$jta = 'active_other_invites';
if (!empty($options['joinTableAlias'])) {
$jta = $joinParams['alias'] = $options['joinTableAlias'];
}
$sugar_query->joinRaw($this->getCustomJoin($options), $joinParams);
return $sugar_query->join[$jta];
}
/**
* Builds main join subpanel
* #param string $params
* #return string JOIN clause
*/
protected function getCustomJoin($params = array())
{
$bean_id = $this->db->quoted($this->focus->id);
$sql = " INNER JOIN(";
$sql .= "SELECT id FROM accounts WHERE id={$bean_id}"; // This is essentially a select statement that will return a set of ids that you can match with the existing sugar_query
$sql .= ") accounts_result ON accounts_result.id = sugar_query_table.id";
return $sql;
}
}
The argument $sugar_query is a new SugarQuery object, the details of which are documented here. What you essentially need to do is extend this query with whatever join/filters you wish to add. This is done in the inner join I've specified.
Note: The inner join can get really complicated, so if you want a real working example, checkout modules/Emails/ArchivedEmailsLink.php and how the core sugar team use this. I can confirm however that this does work with custom joins.
Here is the getEmailsJoin to help you understand what you can actually produce via this custom join.
/**
* Builds main join for archived emails
* #param string $params
* #return string JOIN clause
*/
protected function getEmailsJoin($params = array())
{
$bean_id = $this->db->quoted($this->focus->id);
if (!empty($params['join_table_alias'])) {
$table_name = $params['join_table_alias'];
} else {
$table_name = 'emails';
}
return "INNER JOIN (\n".
// directly assigned emails
"select eb.email_id, 'direct' source FROM emails_beans eb where eb.bean_module = '{$this->focus->module_dir}'
AND eb.bean_id = $bean_id AND eb.deleted=0\n" .
" UNION ".
// Related by directly by email
"select DISTINCT eear.email_id, 'relate' source from emails_email_addr_rel eear INNER JOIN email_addr_bean_rel eabr
ON eabr.bean_id = $bean_id AND eabr.bean_module = '{$this->focus->module_dir}' AND
eabr.email_address_id = eear.email_address_id and eabr.deleted=0 where eear.deleted=0\n" .
") email_ids ON $table_name.id=email_ids.email_id ";
}
Add a new vardef entry for the link field.
For this example, I'm going to create the custom link on the contacts module. So this code goes in custom/Extension/modules/Contacts/Ext/Vardefs/your_field_name.php
<?php
$dictionary["Contact"]["fields"]["your_field_name"] = array(
'name' => 'active_other_invites',
'type' => 'link',
'link_file' => 'custom/modules/<YourModule>/YourNewLink.php',
'link_class' => 'YourNewLink',
'source' => 'non-db',
'vname' => 'LBL_NEW_LINK',
'module' => '<YourModule>',
'link_type' => 'many',
'relationship' => '',
);
Add the new link as a subpanel
This goes under custom/Extension/modules/Contacts/Ext/clients/base/layouts/subpanels/your_subpanel_name.php
<?php
$viewdefs['Contacts']['base']['layout']['subpanels']['components'][] = array (
'layout' => 'subpanel',
'label' => 'LBL_NEW_LINK',
'context' =>
array (
'link' => 'your_field_name',
),
);
Add the label
Under
custom/Extension/modules/Contacts/Ext/Language/en_us.new_link.php
<?php
$mod_strings['LBL_ACTIVE_OTHER_INVITES'] = 'Your New Link';
Quick Repair and Rebuild
That should hopefully get you started. Keep an eye on the sugarlogs while you're debugging your queries. I also found using xdebug and SugarQueries compileSql function invaluable in figuring out what I needed to do to get a working INNER JOIN statement.
I've found this to be a surprisingly powerful solution, it means that if you need to show information related to a module that might be a few joins away, this allows you to create the links manually without having to create pointless related fields in-between the two.

How to add "order by" on a Magento Query

I installed a script for magento. It allows to add comments on orders. So it shows ONE comment on order grid.
The problem is that it doesn't sort comment by "created_at" column. I don't know how to set the order.
This is the portion of code:
protected function _initSelect()
{
parent::_initSelect();
// Join order comment
$this->getSelect()->joinLeft(
array('ordercomment_table' => $this->getTable('sales/order_status_history')),
'main_table.entity_id = ordercomment_table.parent_id AND ordercomment_table.comment IS NOT NULL',
array(
'ordercomment' => 'ordercomment_table.comment',
)
)->group('main_table.entity_id');
return $this;
}
Thanks for your help.
protected function _initSelect()
{
parent::_initSelect();
// Join order comment
$this->getSelect()->joinLeft(
array('ordercomment_table' => $this->getTable('sales/order_status_history')),
'main_table.entity_id = ordercomment_table.parent_id AND ordercomment_table.comment IS NOT NULL',
array(
'ordercomment' => 'ordercomment_table.comment',
)
)->group('main_table.entity_id');
//Add ORDER BY
$this->getSelect()->order(array('ordercomment_table.created_at DESC'));
return $this;
}
Replace this line in the above existing function. Add an ORDER BY.
$this->getSelect()->order('ordercomment_table.created_at', 'DESC');