tax_query to get posts with a field with empty value? - metadata

I defined a custom field, to be able to hide posts from home, like this:
/* Campo adicional que puede ocultar noticia de la home */
function mnd_get_custom_field( $value ) {
global $post;
$custom_field = get_post_meta( $post->ID, $value, true );
if ( !empty( $custom_field ) )
return is_array( $custom_field ) ? stripslashes_deep( $custom_field ) : stripslashes( wp_kses_decode_entities( $custom_field ) );
return false;
}
function mnd_add_custom_meta_box() {
add_meta_box( 'home-page', __( 'Home page', 'mnd' ), 'mnd_meta_box_output', 'post', 'normal', 'high' );
}
add_action( 'add_meta_boxes', 'mnd_add_custom_meta_box' );
function mnd_meta_box_output( $post ) {
wp_nonce_field( 'my_mnd_meta_box_nonce', 'mnd_meta_box_nonce' ); ?>
<p>
<label for="mnd_hide_homepage"><?php _e( 'Hide from homepage', 'mnd' ); ?>:</label>
<input type="checkbox" name="mnd_hide_homepage" id="mnd_hide_homepage" checked="<?php echo mnd_get_custom_field( 'mnd_hide_homepage' ) == 1 ? 'checked' : ''; ?>" value="1" size="50" />
</p>
<?php
}
function mnd_meta_box_save( $post_id ) {
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if( !isset( $_POST['mnd_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['mnd_meta_box_nonce'], 'my_mnd_meta_box_nonce' ) ) return;
if( !current_user_can( 'edit_post', get_the_id() ) ) return;
if( isset( $_POST['mnd_hide_homepage'] ) )
update_post_meta( $post_id, 'mnd_hide_homepage', esc_attr( $_POST['mnd_hide_homepage'] ) );
}
add_action( 'save_post', 'mnd_meta_box_save' );
and I'm trying like:
// The Query
$ppp = 12;
$page = $_GET['page'];
$args_count = array(
'post_type' => 'post',
'paged' => false,
'status' => 'publish'
);
$posts_home_count = new WP_Query( $args_count );
$manyPosts = $posts_home_count->found_posts;
$paginas = $manyPosts / $ppp;
wp_reset_postdata();
$meta_params = array(
array(
'key' => 'mnd_hide_homepage',
'value' => 1,
'compare' => '!=',
'type' => 'NUMERIC'
)
);
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'paged' => $page,
'page' => $page,
'status' => 'publish'/*,
'meta_query' => $meta_params */
);
//print_r ( $args );
$posts_home = new WP_Query( $args );
And it won't return any posts,
But if I change to
'compare' => '=',
Then it returns all the checked posts
Any idea what I'm missing?

There are some problems with Meta Query sometimes and the problem is not always visible. Try the following:
var_dump the WP_Query object and check the SQL manually. Do you see the problem?
Did you try to remove 'type' => 'NUMERIC'?
The “hack” solution (untested):
global $wpdb;
$ids = $wpdb->get_results("
SELECT $wpdb->posts.id FROM $wpdb->posts
WHERE post_status=publish
INNER JOIN $wpdb->post_meta
ON $wpdb->post_meta.post_id = $wpdb->posts.id
AND $wpdb->post_meta.key = 'mnd_hide_homepage'
AND $wpdb->post_meta.value != '1'
");
// put the ids with post__in into the WP_Query arguments
Maybe this is the solution. If not, it may help to find it.

Try this:
array(
'key' => 'mnd_hide_homepage',
'value' => '1',
'compare' => '!=',
'type' => 'NUMERIC'
)
Or
array(
'key' => 'mnd_hide_homepage',
'value' => array('1'),
'compare' => 'NOT IN'
)

Related

Custom FacetWP dropdown not showing posts

I have been able to render a dropdown facet in FacetWP front end with:
add_filter( 'facetwp_facet_html', function( $output, $params ) {
if ( 'today_or_month' == $params['facet']['name'] ) {
$selected = isset( $params['selected'] ) ? $params['selected'] : '';
$output = '<select class="facetwp-dropdown">';
$output .= '<option value="">Select date range</option>';
$output .= '<option value="today"' . ( 'today' == $selected ? ' selected' : '' ) . '>Today</option>';
$output .= '<option value="month"' . ( 'month' == $selected ? ' selected' : '' ) . '>This Month</option>';
$output .= '<option value="test"' . ( 'test' == $selected ? ' selected' : '' ) . '>Test</option>';
$output .= '</select>';
}
return $output;
}, 10, 2 );
All 'event' posts show under the Facet dropdown on page load but when I select an option from the dropdown the queries do not return any posts in the FacetWP template. When I select "Select date range" again all the posts show again.
The queries are as follows:
add_filter( 'facetwp_query_args', function( $args, $class ) {
if (!isset($class->http_params['get']['facetwp'])) return $args;
$selected = $class->http_params['get']['facetwp']['today_or_month'];
$current_month = date( 'Y-m' );
if ( 'today' == $selected ) {
$args['meta_query'][] = array(
'key' => 'event_date_start',
'value' => date( 'Y-m-d' ),
'compare' => '<=',
);
$args['meta_query'][] = array(
'key' => 'event_date_end',
'value' => date( 'Y-m-d' ),
'compare' => '>=',
);
}
elseif ( 'month' == $selected ) {
$args['meta_query'][] = array(
'key' => 'event_date_start',
'value' => date( 'Y-m-01' ),
'compare' => '>=',
);
$args['meta_query'][] = array(
'key' => 'event_date_end',
'value' => date( 'Y-m-t' ),
'compare' => '<=',
);
}
elseif ( 'test' == $selected ) {
$args['meta_query'][] = array(
'key' => 'event_date_start',
'value' => $current_month,
'compare' => 'LIKE',
);
}
$args['post_type'] = 'event';
return $args;
}, 10, 2 );
Does anybody know why the query is not returning any posts in the front end?
I thought maybe I need to convert to a timestamp from ACF custom fields first? Something like this:
$start_date = get_field( 'event_date_start', $params['post_id'] );
$end_date = get_field( 'event_date_end', $params['post_id'] );
$start_timestamp = strtotime( $start_date );
$end_timestamp = strtotime( $end_date );
And then use these variables as the key:
'key' => '$start_timestamp ',
Any help at all would be great. Been going over and over this! Thank you so much. I am begging.
I have tried to run the code as above, I expected some of the custom post types of event to show up in the FacetWP template area according to the dropdown selections. Instead no posts show at all (they should show as some of the posts have February dates).

update_post_meta for properties visibility?

I'm trying to find how can I display the list of imported properties. The problem is the metadata, after import the properties are not visible on the frontend and I need to update every item manually. How can I update metadata editing a following code:
<?php
$args = array(
'posts_per_page' => $custom_property_items_amount,
'post_type' => 'property',
'orderby' => array(
'menu_order'=>'ASC',
'date' =>'DESC',
),
'offset' => ( max( 1, get_query_var( 'paged' ) ) - 1 ) * $custom_property_items_amount,
'ignore_sticky_posts' => 1,
'post_status' => array('publish','pending','draft','future','private'),
);
$data = new WP_Query( $args );
?>
<div class="<?php echo join( ' ', $wrapper_classes ) ?>">
<?php if ( $data->have_posts() ) :
while ( $data->have_posts() ): $data->the_post(); ?>
<?php ere_get_template( 'content-property.php', array(
'custom_property_image_size' => $custom_property_image_size,
'property_item_class' => $property_item_class
)); ?>
<?php endwhile;
else: ?>
<div class="item-not-found"><?php esc_html_e( 'Not found', 'essential-real-estate' ); ?></div>
<?php endif; ?>
<div class="clearfix"></div>
<?php
$max_num_pages = $data->max_num_pages;
ere_get_template( 'global/pagination.php', array( 'max_num_pages' => $max_num_pages ) );
wp_reset_postdata(); ?>
</div>
Solved! The problem was in this part of the code:
if (!empty($features)) {
foreach($features as $feature){
$tax_query[] = array(
'taxonomy' => 'property-feature',
'field' => 'slug',
'terms' => $feature
);
$parameters.=sprintf( __('Feature: <strong>%s</strong>; ', 'essential-real-estate'), $feature);
}
}
$args['meta_query'] = array(
'relation' => 'AND',
$meta_query
);
$tax_count = count($tax_query);
if ($tax_count > 0) {
$args['tax_query'] = array(
'relation' => 'AND',
$tax_query
);
}
By deleting this all the items were displayed.

Fedex SOAP Request Failing

I am looking for the reason why the below request is failing to retrieve information. This is copied from the Fedex developer website and it doesn't work. When my program hits the GetRates line it throws a could not connect to host exception. I tried adding the connection_timeout and setting the default_timeout in php and neither appear to work. I contacted the Fedex dev team and they are receiving my post successfully I am just not able to get any response besides the fault. Has anyone had experience with Fedex or know what might cause this to be failing?
I am posting my current code below. I am using PHP7 on an AS400 machine using Zendserver.
<?php
// Copyright 2009, FedEx Corporation. All rights reserved.
// Version 12.0.0
require_once('../library/fedex-common.php5');
$newline = "<br />";
//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "../wsdl/RateService_v24.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
ini_set('soap.wsdl_cache_ttl',0);
$client = new SoapClient($path_to_wsdl, array('trace' => 1, 'connection_timeout' => 30)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
'ParentCredential' => array(
'Key' => getProperty('parentkey'),
'Password' => getProperty('parentpassword')
),
'UserCredential' => array(
'Key' => getProperty('key'),
'Password' => getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'),
'MeterNumber' => getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '24',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
$request['RequestedShipment']['TotalInsuredValue']=array(
'Ammount'=>100,
'Currency'=>'USD'
);
$request['RequestedShipment']['Shipper'] = addShipper();
$request['RequestedShipment']['Recipient'] = addRecipient();
$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1();
try {
if(setEndpoint('changeEndpoint')){
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client -> getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR'){
$rateReply = $response -> RateReplyDetails;
echo '<table border="1">';
echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>';
$serviceType = '<td>'.$rateReply -> ServiceType . '</td>';
if($rateReply->RatedShipmentDetails && is_array($rateReply->RatedShipmentDetails)){
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
}elseif($rateReply->RatedShipmentDetails && ! is_array($rateReply->RatedShipmentDetails)){
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
}
if(array_key_exists('DeliveryTimestamp',$rateReply)){
$deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>';
}else if(array_key_exists('TransitTime',$rateReply)){
$deliveryDate= '<td>' . $rateReply->TransitTime . '</td>';
}else {
$deliveryDate='<td> </td>';
}
echo $serviceType . $amount. $deliveryDate;
echo '</tr>';
echo '</table>';
printSuccess($client, $response);
}else{
printError($client, $response);
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
function addShipper(){
$shipper = array(
'Contact' => array(
'PersonName' => 'Sender Name',
'CompanyName' => 'Sender Company Name',
'PhoneNumber' => '9012638716'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Collierville',
'StateOrProvinceCode' => 'TN',
'PostalCode' => '38017',
'CountryCode' => 'US'
)
);
return $shipper;
}
function addRecipient(){
$recipient = array(
'Contact' => array(
'PersonName' => 'Recipient Name',
'CompanyName' => 'Company Name',
'PhoneNumber' => '9012637906'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Richmond',
'StateOrProvinceCode' => 'BC',
'PostalCode' => 'V7C4V4',
'CountryCode' => 'CA',
'Residential' => false
)
);
return $recipient;
}
function addShippingChargesPayment(){
$shippingChargesPayment = array(
'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
'CountryCode' => 'US'
)
)
);
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
'ImageType' => 'PDF', // valid values DPL, EPL2, PDF, ZPLII and PNG
'LabelStockType' => 'PAPER_7X4.75'
);
return $labelSpecification;
}
function addSpecialServices(){
$specialServices = array(
'SpecialServiceTypes' => array('COD'),
'CodDetail' => array(
'CodCollectionAmount' => array(
'Currency' => 'USD',
'Amount' => 150
),
'CollectionType' => 'ANY' // ANY, GUARANTEED_FUNDS
)
);
return $specialServices;
}
function addPackageLineItem1(){
$packageLineItem = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => 50.0,
'Units' => 'LB'
),
'Dimensions' => array(
'Length' => 108,
'Width' => 5,
'Height' => 5,
'Units' => 'IN'
)
);
return $packageLineItem;
}
?>

Paragraph breaks missing from shortcode output

I created a shortcode in Wordpress to perform a query and display the content, but the content line breaks are being removed.
add_shortcode( 'resource' , 'Resource' );
function Resource($atts) {
$atts = shortcode_atts( array(
'category' => ''
), $atts );
$categories = explode(',' , $atts['category']);
$args = array(
'post_type' => 'resource',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page'=> -1,
'tax_query' => array( array(
'taxonomy' => 'category',
'field' => 'term_id',
'operator' => 'AND',
'terms' => $categories
) )
);
$string = '';
$query = new WP_Query( $args );
if( ! $query->have_posts() ) {
$string .= '<p>no listings at this time...</p>';
}
while( $query->have_posts() ){
$query->the_post();
$string .= '<div id="links"><div id="linksImage">' . get_the_post_thumbnail() . '</div>
<div id="linksDetails"><h1>'. get_the_title() .'</h1><p>' . get_the_content() . '</p>
<p>for more information CLICK HERE</div></div>';
}
wp_reset_postdata();
$output = '<div id="linksWrapper">' . $string . '</div>';
return $output;
}
Any suggestion on why this is happening and what to do to fix it. This is only happening on the shortcode output. On regular pages - the content displays correctly.
found a solution through more searches:
function get_the_content_with_formatting ($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
works perfect, so I thought I would share..

How to increase picture using html code with yii2 syntax?

Hy guys, following code will increase picture by clicking on it:
<a class="example-image-link" href="http://lokeshdhakar.com/projects/lightbox2/images/image-1.jpg"><img src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-1.jpg" alt="image-1" /></a>
)
In my yii2 application, I have following valid picture-url in anonymous function:
$url = '#web/img/' . $bild->dateiname;
How to tranform upper code in yii2 syntax. I try like this, but it's not working:
return Html::a(
Html::img($url, ['alt' => 'PicNotFound', 'class' => 'img-circle', 'style' => 'width:225px;height:225px']
), [Html::img($url, ['alt' => 'PicNotFound']
)], ['title' => 'Immobiliendaten abrufen', 'data' => ['pjax' => '0'], 'class' => 'example-image-link']
);
Firedebug will show following html-code. url in link is wrong!
a class="example-image-link" href="/yii2_ErkanImmo/frontend/web/index.php/" title="Immobiliendaten abrufen"><img class="img-circle" src="/yii2_ErkanImmo/frontend/web/img/villa1.jpg" alt="PicNotFound" style="width:125px;height:125px;">event
<img class="img-circle" src="/yii2_ErkanImmo/frontend/web/img/villa1.jpg" alt="PicNotFound" style="width:125px;height:125px;">
</a>
Rephrasing question
I will get output as shown up at my attachement after having clicked on picture using code like this:
return Html::a(Html::img($url, ['alt' => 'image-1']), $url, ['class' => 'example-image-link']);[![enter image description here][1]][1]
Here is complete code of view file(for GRU)
[
'attribute' => $dummy,
'label' => Yii::t('app', ''),
'format' => 'html', // sorgt dafür,dass das HTML im return gerendert wird
'vAlign' => 'middle',
'value' => function($model) {
$bmp = '/bmp/';
$tif = '/tif/';
$png = '/png/';
$psd = '/psd/';
$pcx = '/pcx/';
$gif = '/gif/';
$jpeg = '/jpeg/';
$jpg = '/jpg/';
$ico = '/ico/';
try {
$bilder = \frontend\models\Dateianhang::GetBild($model);
foreach ($bilder as $bild) {
if (preg_match($bmp, $bild->dateiname) || preg_match($tif, $bild->dateiname) || preg_match($png, $bild->dateiname) || preg_match($psd, $bild->dateiname) || preg_match($pcx, $bild->dateiname) || preg_match($gif, $bild->dateiname) || preg_match($jpeg, $bild->dateiname) || preg_match($jpg, $bild->dateiname) || preg_match($ico, $bild->dateiname)) {
$url = '#web/img/' . $bild->dateiname;
}
}
return Html::a(Html::img($url, ['alt' => 'image-1', 'class' => 'img-circle', 'style' => 'width:225px;height:225px']), $url, ['class' => 'example-image-link', 'title' => 'Touch picture to increase', 'target' => '_blank']);
//return Html::img($url, ['alt' => 'Bewerberbild nicht vorhanden', 'class' => 'img-circle', 'style' => 'width:225px;height:225px']);
} catch (Exception $e) {
return;
}
}
],
Neither picture will be increased, nor target=>_blank is doing its job :=(
Try following code -
<?php
$url = 'http://lokeshdhakar.com/projects/lightbox2/images/thumb-1.jpg';
//in your case
//$url = '#web/img/'.$bild->dateiname;
echo Html::a(
Html::img($url, ['alt'=>'image-1']),
$url, ['class'=>'example-image-link']);
?>
If you want to redirect to some action in controller, replace $url in last line with ['/controller/action']