Meta query key with POST OBJECT (ACF) (post_title) in wordpress - php

I have big problem with my meta query. I would like to filter my posts, and I need query to compare post_title with my $_POST value.
Code:
function postsFilter(){
$args = array(
'post_type' => 'posts',
'meta_query' => array(
'relation' => 'AND'
)
);
if( isset($_POST['year']) && $_POST['year'] )
$args['meta_query'][] = array(
'key' => 'year',
'value' => $_POST['year'],
'compare' => '='
);
if( isset($_POST['theme']) && $_POST['theme'] )
$args['meta_query'][] = array(
'key' => 'theme',
'value' => $_POST['theme'],
'compare' => '='
);
if( isset($_POST['member']) && $_POST['member'] )
$args['meta_query'][] = array(
'key' => 'member_relation',
'value' => ``.$_POST['member'].``,
'compare' => 'LIKE'
);
$query = new WP_Query( $args );
echo "<script>
var posts_p = '" . json_encode( $query->query_vars ) . "',
current_page_p = " . 1 . " ,
max_page_p = " . $query->max_num_pages . ";
console.log(current_page_p, max_page_p);
</script>";
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
get_template_part('template-parts/content', 'posts');
endwhile;
if ( $query->max_num_pages > 1 )
echo '<div class="button-load-more_p btn-load-more text-center mx-auto w-100"><a class="btn btn-primary btn-md btn-with-icon fade-in full-visible load-more"><span>Load more</span></div></a></div>';
wp_reset_postdata();
else :
echo 'No publications found';
endif;
die();
}
and problem exists here:
if( isset($_POST['member']) && $_POST['member'] )
$args['meta_query'][] = array(
'key' => 'member_relation',
'value' => $_POST['member']
'compare' => 'LIKE'
);
because I don't know how to write this part of query,
member relation is POST OBJECT type file in Wordpress, I need compare $_POST['member'] with post_title value (maybe I am wrong ?)
$member = get_field('member_relation', $post_object->ID);
$member->post_title;
Is it possible to write this query? Please give me any advice or example solution of my problem.

Try This, merge your meta query argument with the post title arg.
if( isset( $_POST['title'] ) && !empty( $_POST['title'] ) ){
$args2 = array(
's' => '"'.$_POST['title'].'"'
) ;
$args = array_merge( $args, $args2);
}

Related

Add a Post sorting drop-down list inside custom WP_Query

I have a wp_Query loop with working search filters and filters.
I would like to integrate a drop-down menu that sorts posts filtered or not by price and date.
When I try it does not order me anything as if it was not possible I think some parameters are missing inside my custom wp_Query
I have tried several ways but to no avail, help me please
Function.php
function search_query()
{
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = [
'paged' => $paged,
'post_type' => 'cars',
'posts_per_page' => 0,
'tax_query' => [],
'meta_query' => [
'relation' => 'AND',
],
];
if( isset($_GET['key']) )
{
if(!empty($_GET['key']))
{
$args['s'] = sanitize_text_field( $_GET['key'] );
}
}
if( isset($_GET['prov']) )
{
if(!empty($_GET['prov']))
{
$args['tax_query'][] = [
'taxonomy' => 'prov',
'field' => 'slug',
'terms' => array( sanitize_text_field( $_GET['prov'] ) )];
}
}
if( isset($_GET['price_above']) )
{
if(!empty($_GET['price_above']))
{
$args['meta_query'][] = array(
'key' => 'pricefinal',
'value' => sanitize_text_field( $_GET['price_above']) ,
'type' => 'numeric',
'compare' => '>='
);
}
}
if( isset($_GET['price_below']) )
{
if(!empty($_GET['price_below']))
{
$args['meta_query'][] = array(
'key' => 'pricefinal',
'value' => sanitize_text_field( $_GET['price_below']) ,
'type' => 'numeric',
'compare' => '<='
);
}
}
return new WP_Query($args);
}
HTML
<form action="<?php print home_url('/cerca-cars'); ?>" method="get">
<div class="form-group">
<select class="form-control" name="sortposts">
<option value="date"
<?php echo selected($_GET['orderby'], 'date'); ?>
>
New
</option>
<option value="property_price-ASC">Prezzo Crescente</option>
<option value="property_price-DESC">Prezzo Descrescente</option>
<input
id="order"
type="hidden"
name="order"
value="<?php echo (isset($_GET['order']) && $_GET['order'] == 'ASC') ? 'ASC' : 'DESC'; ?>"
/>
<button type="submit" class="btn btn-success btn-lg btn-block">ORDINA</button>
</select>
<?php
global $query;
// let's create new array with args
if( !empty( $_GET['sortposts'] ) ) {
// I recommend to explode it because we're take 2 param values from one $_GET variable
$sort_args = explode( "-", $_GET['sortposts'] );
// $sort_args[0] is what we sort
// $sort_args[1] is how we sort - Ascending or Descending
$new_args['order'] = $sort_args[1];
if( $sort_args[0] == 'date' ) {
// date is a default WP_Query value, so we do nothing
$new_args['orderby'] == 'date';
} elseif( $sort_args[0] == 'property_price' ) {
$new_args['orderby'] = 'meta_value_num';
$new_args['meta_key'] = 'pricefinal';
}
}
$args = array_merge( $query->query_vars, $new_args ); query_posts( $args );?>
<?php $query = search_query(); ?>
<?php if( $query->have_posts() ) :?>
<?php while ($query->have_posts()) : $query->the_post(); ?>

Adding 'sort by' drop down on custom page using woocommerce short code

I have created a custom page using woocommerce short code for product categories. At the moment, it's pretty sparse as I've only just started on the new site.
I just need the default 'sort by' drop down element adding but have no idea how to do it.
I found some code here >>Woocommerce, sort dropdown on shortcode based product lists
and it certainly placed the drop down I need on the site (although I'd like it aligned left).
The only problem now, is that it's displaying the products with enormous images and all in a single vertical column.
I'm not a PHP programmer and am wondering if I've deleted some important code in the php file I modified. (thank god I took a copy of the original!).
Can anyone help? Is there a better way to add the sort by drop down onto my custom pages?
This is one of the pages I've created >> http://www.sdmtest1.co.uk/notebooks-journals/
Here is the code I added.
/**
* List products in a category shortcode
*
* #param array $atts
* #return string
*/
public static function product_category( $atts ) {
$atts = shortcode_atts( array(
'per_page' => '12',
'columns' => '4',
'orderby' => 'title',
'order' => 'desc',
'category' => '', // Slugs
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
), $atts );
if ( ! $atts['category'] ) {
return '';
}
// Default ordering args
$ordering_args = WC()->query->get_catalog_ordering_args( $atts['orderby'],
$atts['order'] );
$orderby = 'title';
$order = 'asc';
if ( isset( $_GET['orderby'] ) ) {
$getorderby = $_GET['orderby'];
}
if ($getorderby == 'popularity') {
$orderby = 'meta_value_num';
$order = 'desc';
$meta_key = 'total_sales';
} elseif ($getorderby == 'rating') {
$fields .= ", AVG( $wpdb->commentmeta.meta_value ) as average_rating ";
$where .= " AND ( $wpdb->commentmeta.meta_key = 'rating' OR $wpdb->commentmeta.meta_key IS null ) ";
$join .= "
LEFT OUTER JOIN $wpdb->comments ON($wpdb->posts.ID = $wpdb->comments.comment_post_ID)
LEFT JOIN $wpdb->commentmeta ON($wpdb->comments.comment_ID = $wpdb->commentmeta.comment_id)
";
$orderby = "average_rating DESC, $wpdb->posts.post_date DESC";
$groupby = "$wpdb->posts.ID";
} elseif ($getorderby == 'date') {
$orderby = 'date';
$order = 'desc';
} elseif ($getorderby == 'price') {
$orderby = 'meta_value_num';
$order = 'asc';
$meta_key = '_price';
} elseif ($getorderby == 'price-desc') {
$orderby = 'meta_value_num';
$order = 'desc';
$meta_key = '_price';
}
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'orderby' => $orderby, // $ordering_args['orderby'],
'order' => $order, // $ordering_args['order'],
'meta_key' => $meta_key,
'fields' => $fields,
'where' => $where,
'join' => $join,
'groupby' => $groupby,
'posts_per_page' => $per_page,
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => array( esc_attr( $category ) ),
'field' => 'slug',
'operator' => $operator
)
)
);
if ( isset( $ordering_args['meta_key'] ) ) {
$args['meta_key'] = $ordering_args['meta_key'];
}
ob_start();
$products = new WP_Query( apply_filters( 'woocommerce_shortcode_products_query', $args, $atts ) );
$woocommerce_loop['columns'] = $columns;
if ( $products->have_posts() ) : ?>
<div style="width:100%;">
<div style="float:right">
<form class="woocommerce-ordering" method="get">
<select name="orderby" class="orderby">
<?php
$catalog_orderby = apply_filters( 'woocommerce_catalog_orderby', array(
'menu_order' => __( 'Default sorting', 'woocommerce' ),
'popularity' => __( 'Sort by popularity', 'woocommerce' ),
'rating' => __( 'Sort by average rating', 'woocommerce' ),
'date' => __( 'Sort by newness', 'woocommerce' ),
'price' => __( 'Sort by price: low to high', 'woocommerce' ),
'price-desc' => __( 'Sort by price: high to low', 'woocommerce' )
) );
if ( get_option( 'woocommerce_enable_review_rating' ) === 'no' )
unset( $catalog_orderby['rating'] );
foreach ( $catalog_orderby as $id => $name )
echo '<option value="' . esc_attr( $id ) . '" ' . selected( $getorderby, $id, false ) . '>' . esc_attr( $name ) . '</option>';
?>
</select>
<?php
// Keep query string vars intact
foreach ( $_GET as $key => $val ) {
if ( 'orderby' === $key || 'submit' === $key )
continue;
if ( is_array( $val ) ) {
foreach( $val as $innerVal ) {
echo '<input type="hidden" name="' . esc_attr( $key ) . '[]" value="' . esc_attr( $innerVal ) . '" />';
}
} else {
echo '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( $val ) . '" />';
}
}
?>
</form>
</div>
</div>
<div style="clear:both;"></div>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
woocommerce_reset_loop();
wp_reset_postdata();
return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';
}
I edited in dreamweaver and it flagged a syntax error. I wasn't sure where the code I pasted was to begin and end and I kinda lost this bit in the process.
// Remove ordering query arguments
WC()->query->remove_ordering_args();
return $return;
}
Thanks,
Loren
If you add the paginate="true" attribute to your [products] shortcode, then the shortcode, then the Sort by dropdown menu will appear on the page.
I have created a custom page using woocommerce short code for product categories.
You say you're using shortcodes, but you don't provide an example. So I'll make one up.
If you were using this to display all of the products in the "boots" category:
[product_category category="boots"]
Then change it to this:
[product_category category="boots" paginate="true"]

Custom query on wordpress author page

I am not expert on php and need some help about custom query on my wordpress author page.
I have no problem when using WP_User_Query, the problem is i need to combine it with $curauth
What i need to do is get authors list with WP_User_Query that filtered with current author page as a custom field value.
here is code that got error:
// WP_User_Query arguments
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
$label = echo $curauth->user_login;
$args = array (
'role' => 'contibutor',
'number' => '10',
'order' => 'ASC',
'orderby' => 'display_name',
'meta_query' => array(
array(
'key' => 'user_label',
'value' => $label,
),
),
);
// The User Query
$user_query = new WP_User_Query( $args );
// The User Loop
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
// do something
}
} else {
// no users found
}
I hope someone here can help to resolve my problem. Thank you
Try this
$curauth = ( isset( $_GET['author_name'] ) ) ? get_user_by( 'slug', $author_name ) : get_userdata( intval( $author ) );
$args = array (
'role' => 'contibutor',
'number' => '10',
'order' => 'ASC',
'orderby' => 'display_name',
'meta_query' => array(
array(
'key' => 'user_label',
'value' => $curauth->user_login,
),
),
);
// The User Query
$user_query = new WP_User_Query( $args );
// The User Loop
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
// do something
}
} else {
// no users found
}
As pointed out by pieter-goosen in the comments, the line $label = echo $curauth->user_login; was causing the error message.

WP Loop Specific Metabox Value From All Post On Custom Post Type

I've created function for loop specific metabox value from all post on custom post type. It's working perfectly. Here are the codes:
$loop = new WP_Query(array('post_type' => 'myposttype', 'posts_per_page' => -1));
while ( $loop->have_posts() ) : $loop->the_post();
$custom_fields = get_post_custom($post->ID);
$my_custom_field = $custom_fields['custommetabox_mb'];
foreach ( $my_custom_field as $key => $value ) {
echo $value . "<br />";
}
endwhile;
Is it possible to just loop some metabox value. Example:
There have 2 metabox on this custom post type.
First = custommetabox_mb
Second = custommetabox_mbb
What I want is, just loop custommetabox_mb if custommetabox_mbb value same with text "yiedpozi".
How can I do this?
use meta_query
$args = array('post_type' => 'myposttype', 'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'custommetabox_mb',
'value' => 'yiedpozi',
'compare' => '='
),
array(
'key' => 'custommetabox_mbb',
'value' => 'yiedpozi',
'compare' => '='
)
), 'posts_per_page' => -1,);
$loop = new WP_Query($args);
while ( $loop->have_posts() ) : $loop->the_post();
$custom_fields = get_post_custom($post->ID);
$my_custom_field = $custom_fields['custommetabox_mb'];
foreach ( $my_custom_field as $key => $value ) {
echo $value . "<br />";
}
endwhile;

Customising excerpt in theme

I've been reading a lot of how to customize excerpt function in WordPress but I have no idea how to proceed with this.
The theme that I am using already have 4 pre-customized excerpt functions and the one that I will show here is closest to my desired but still needs to improve.
My question is how to stop erasing HTML formating from my content (line breaks, paragraphs, font variants, etc)?
add_shortcode('display_news_s5', 'be_display_posts_shortcode5');
function be_display_posts_shortcode5($atts) {
// Pull in shortcode attributes and set defaults
extract( shortcode_atts( array(
'post_type' => 'post',
'post_parent' => false,
'id' => false,
'tag' => '',
'category' => '',
'offset' => 0,
'posts_per_page' => '1',
'order' => 'DESC',
'orderby' => 'date',
'include_date' => false,
'include_excerpt' => false,
'excerpt_l' => 8,
'taxonomy' => false,
'tax_term' => true,
'tax_operator' => 'IN'
), $atts ) );
// Set up initial query for post
$args = array(
'post_type' => explode( ',', $post_type ),
'tag' => $tag,
'category_name' => $category,
'p' => $id,
'posts_per_page' => $posts_per_page,
'order' => $order,
'orderby' => $orderby,
'offset' => $offset
);
// If Post IDs
if( $id ) {
$posts_in = explode( ',', $id );
$args['post__in'] = $posts_in;
}
// If taxonomy attributes, create a taxonomy query
if ( !empty( $taxonomy ) && !empty( $tax_term ) ) {
// Term string to array
$tax_term = explode( ', ', $tax_term );
// Validate operator
if( !in_array( $tax_operator, array( 'IN', 'NOT IN', 'AND' ) ) )
$tax_operator = 'IN';
$tax_args = array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $tax_term,
'operator' => $tax_operator
)
)
);
$args = array_merge( $args, $tax_args );
}
// If post parent attribute, set up parent
if( $post_parent ) {
if( 'current' == $post_parent ) {
global $post;
$post_parent = $post->ID;
}
$args['post_parent'] = $post_parent;
}
$listing = new WP_Query( apply_filters( 'display_posts_shortcode_args', $args, $atts ) );
$count = 0;
if ( !$listing->have_posts() )
return apply_filters ('display_posts_shortcode_no_results', false );
$inner = '';
while ( $listing->have_posts() ): $listing->the_post(); global $post;
$count++;
if( $count == 1 ){
$style = ' news-main-post';
} else {
$style = ' news-list-posts';
}
$title = '<div class="news-listing-title"><a class="title" href="'. get_permalink() .'">'. get_the_title() .'</a></div>';
if ($include_date == 'true') $date = ' <div class="news-listing-meta"><span class="news-listing-date">'. get_the_date() . '</span><span class="news-listing-comment">('. get_comments_number() .')</span></div>';
else $date = '';
if ($include_excerpt == 'true') $excerpt = '<span>' .excerpt($excerpt_l) . '</span>';
else $excerpt = '';
$output = '<div class="news-listing' . $style . '"><div class="news-listing-item">'. $title . $excerpt . $date . '</div></div>';
$inner .= apply_filters( 'display_posts_shortcode_output', $output, $atts, $title, $excerpt, $date );
endwhile; wp_reset_query();
$open = apply_filters( 'display_posts_shortcode_wrapper_open', '<div class="news-listing-wrapper-s3">' );
$close = apply_filters( 'display_posts_shortcode_wrapper_close', '<div class="clear"></div></div>' );
$return = $open . $inner . $close;
return $return;
}
Have a look here: LINK looks like its doing what you want to acchieve.

Categories