WP_Query in wordpress and include ACF in results - wordpress

I try to fetch all posts from a custom post type in Wordpress and include the advanced custom fields (ACF) in the results as well, in order to generate a JSON file with the data.
$query = new WP_Query(array(
'post_type' => 'resources',
'post_status' => 'publish',
'posts_per_page' => -1,
));
echo "var json=". json_encode($query->get_posts());
With a simple WP_Query, ACF data are not included and I have to iterate in the results and fetch all ACF manually one by one. Is there any way to include them in the original WP_Query results?

This would be my way of doing it.
Push whatever you want to the array and encode it.
<?php
$array = array();
$args = array(
'post_type' => 'resources',
'post_status' => array( 'publish' ),
'nopaging' => true,
'posts_per_page' => '-1',
'order' => 'ASC',
'orderby' => 'ID',
);
$queryResults = new WP_Query( $args );
if ( $queryResults->have_posts() ) {
$counter = 0;
while ( $queryResults->have_posts() ) {
$queryResults->the_post();
$array[ $counter ][ 'ID' ] = get_the_ID();
$array[ $counter ][ 'name' ] = get_the_title();
$array[ $counter ][ 'thumbnailURL' ] = get_the_post_thumbnail_url();
$array[ $counter ][ 'place' ] = get_field( 'resource_location' );
//etc etc etc
$counter++;
}
$jasoned = json_encode( $array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
echo $jasoned;
} else {
//nothing found
}
wp_reset_postdata();

You can use get_fields() to fetch all acf fields registered at once with the post. Have a look the documentation here.

To add ACF data in query. WP_Query will not help.
WP_Query does not return values from any custom fields. To get these you must loop through the posts and get the values of the fields.
Refer to this documentation: https://www.advancedcustomfields.com/resources/query-posts-custom-fields/

Related

assign tags to all posts

I want to auto assign some tags to a post category
I am using the wp set post tags function in the functions.php file.
wp_set_post_tags( $post_id, 'tag1,tag2', true );
It works when I put in the post id number. I need help with looping through the posts from a category.
Hope someone can help!
Thanks
You need to write query and then apply the function for it. Let me share coding for this.
For custom post type and taxonomy the following code will work. Make sure to replace post_type , taxonomy and terms according to your value.
$args = array(
'post_type' => 'custom_post_type',
'tax_query' => array(
array(
'taxonomy' => 'custom_taxonomy_name',
'field' => 'term_id',
'terms' => array(1,2,3),
),
),
);
$the_query = new WP_Query($args);
For post type post there the query is simple
$args = array(
'post_type' => 'post',
'category__in' => array(11,12,13)
);
$the_query = new WP_Query( $args );
Make sure to replace category__in with category id you want to run the query.
After that please run the loop
<?php
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
wp_set_post_tags( $the_query->post->ID, 'tag1,tag2', true );
}
} else {
// No post found
}
/* Restore original Post Data */
wp_reset_postdata();
?>

Sort products by most viewed

I'm using a plugin that already count product views and store it in a table called 'mwb_wpr_data'.
The query to list the product views is:
SELECT DISTINCT('productid') FROM 'mwb_wpr_data' WHERE 'action' = 'view'
The productid field is a FK to Woocomerce products.
How can I modify the Woocommerce default sorting, so it will display products by order of most views based in the table 'mwb_wpr_data'?
Current code using the plugin Post View Counter:
add_action( 'pre_get_posts', 'my_view_filter' );
function my_view_filter($query){
if (
$query->is_main_query() &&
( $query->is_home() || $query->is_archive() || $query->is_search() )
) {
$query->set('suppress_filters', 'false');
$query->set('orderby', 'post_views');
$query->set('order', 'DESC');
}
}
According to me you have set the correct pre_get_post but problem is in your if condition.
You have set the current_user_can which not correct filter is for every user so if you are not login in with administrator role than your query will not work.
current_user_can('administrator')
Remove this above one from the condition.
add_action( 'pre_get_posts', 'my_view_filter' );
function my_view_filter($query){
if ($query->is_main_query() && ( $query->is_home() || $query->is_archive() || $query->is_search() )
) {
$query->set('suppress_filters', 'false');
$query->set('orderby', 'post_views');
$query->set('order', 'DESC');
}
}
Ok, so the RIGHT way to do this would be
Change how your post view counts are stored, so that they are stored as postmeta of each product (post) in a field like _post_views_count.
Use meta_key & orderby in wp_query like this
$args = array(
'meta_key' => '_post_views_count',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
< EDIT >
IF you want to use the same plugin for recording your product views, I'd set up a function that fires every time a post view is added to the table that updates a postmeta field of the product.
Is it elegant? No.
Will it work? Yes.
Not sure about the plugin you're using (it would be great if you give additional info about it) but I've been using Post Views Counter for years and it works really well.
It even has a query parameter for WP_Query (to query posts by post views):
EDIT: This query parameter won't work without the Post Views Counter plugin as it's not a WordPress default parameter.
More info about this plugin API here:
https://dfactory.eu/docs/post-views-counter/developers-api/
$query_args = array(
'posts_per_page' => 12,
'order' => 'DESC',
'suppress_filters' => false, //required param
'orderby' => 'post_views', //required param
);
$query = new WP_Query( $query_args );
if ( $query->have_posts() ):
while ( $query->have_posts() ): $query->the_post();
//Post content here
echo get_the_title();
endwhile;
endif;
I hope this helps,
Cheers!
According to the plugins documentation you are required to pass the post_type as well in order for this to work, i.e.
$args = array(
'order' => 'asc',
'post_type' => 'event',
// required by PVC
'suppress_filters' => false,
'orderby' => 'post_views',
'fields' => ''
);
$most_viewed = get_posts( $args );
That code is in the post that #Marounm linked to in comment higher up.
Try passing the post_type arg as well i.e.
$query->set('post_type', 'product');
If you want to showing the the products which was most viewed , so you can follow these below steps .
Steps :1 I have add menu in admin panel using (add_menu_page) function. in function file
function admin_manage_users22(){
add_menu_page('My Page Title', 'MVP', 'manage_options', 'MVP_backend_view',
'MVP_backend_view' );
}
add_action('admin_menu', 'admin_manage_users22');
Step :2 Get product details after user view product it's +1 counter value in wp_postmeta with post id. default value set 1
function MVP_product_details($product ) {
$post_id = get_the_ID();
$count_key = 'AK_product_view_count';
$count = get_post_meta( $post_id, $count_key, true );
if ( empty( $count ) ) {
delete_post_meta( $post_id, $count_key );
update_post_meta( $post_id, $count_key, '1' );
echo "count null";
}else{
$count ++;
update_post_meta( $post_id, $count_key, (string) $count );
}
}
add_filter( 'woocommerce_quantity_input_args', 'MVP_product_details', 10, 2 );
Step :3 Now you can get most viewed product details simply using below code.
function MVP_backend_view(){
$count_key = 'AK_product_view_count';
$query_args = array(
'posts_per_page' => 3,
'no_found_rows' => 1,
'post_status' => 'publish',
'post_type' => 'product',
'orderby' => 'meta_value',
'order' => 'DESC',
'meta_key' => $count_key,
);
$query_args['meta_query'] = array(
array(
'key' => $count_key,
'value' => '0',
'type' => 'numeric',
'compare' => '>',
),
);
$zwcmvp_query = new WP_Query( $query_args );

How to get Last post Id of custom post type in wordpress

I want to get the last post id of a custom post type in WordPress. For this, I tried this code-
$args = array(
'post_type' =>'soto_property',
'posts_per_page' => 1,
'orderby'=>'post_date',
'order' => 'DESC',
);
$image_posts = get_posts($args);
foreach ( $image_posts as $post ) {
echo $post->ID;
}
But It always returns me the First post id of this custom post type. I have tried 'order'=>'ASC' also but it gives me the same result.
How can I achieve the last post id of this CPT?
you can use wp_get_recent_posts function.
Here's a sample function:
$args = array(
'post_type' =>'soto_property',
'posts_per_page' => 1
);
$recent_post = wp_get_recent_posts($args, OBJECT);
Check function reference page in codex for more information.
try to use WP_Query
$args=array(
'post_type' => 'soto_property',
'posts_per_page' => 1,
'caller_get_posts'=> 1,
'orderby' => 'id',
'order' => 'DESC'
);
$query = new WP_Query($args);
foreach ($query as $key) {
$last_soto_property = $key->ID;
}
var_dump($last_soto_property);
this will show the ID of your last custom post type.
I have got my last inserted Post id using $wpdb query as below-
global $wpdb;
$lastrowId=$wpdb->get_col( "SELECT ID FROM wp_posts where post_type='soto_property' ORDER BY post_date DESC " );
$lastPropertyId=$lastrowId[0];
Your PHP code contains one small mistake:
posts_per_page is set to 1. it should be higher than one. This is why you are getting only one result out of the results that were queried.
So instead of 'posts_per_page' => 1 you could use 'posts_per_page' => your_desired_number_of_post_here
Your complete code should look like:
$args = array(
'post_type' =>'soto_property',
'posts_per_page' => your_desired_number_of_post_here,
'orderby'=>'post_date',
'order' => 'DESC',
);
$image_posts = get_posts($args);
foreach ( $image_posts as $post )
{
echo $post->ID;
}

How to query on custom fields in Wordpress?

I'm trying to query posts based on a custom field, and then display them in a loop. I've checked and double checked my code against the codex and other sources, but the query still does not appear to be working. What am I doing wrong?
Stripped down to the essentials, my code looks like this:
<?php
$args = array(
'meta_key' => 'my_custom_field'
);
$my_query = new WP_Query( $args );
?>
<?php if ( $my_query->have_posts() ) { ?>
<p>Success, we have posts!!!</p>
<?php } else { ?>
<p>Uh Oh, No posts!!!</p>
<?php } ?>
The conditional statement is dropping through and returning "Uh Oh, no posts".
I've checked the postmeta table, and there are definitely posts that contain the meta_key _my_custom_field. I have tried the query both with and without leading underscore.
What am I doing wrong?
I use this for search a date between two custom dates field in my custom post type "porfolio", i think that you are in a similar situation:
$args = array(
'post_type' => 'portfolio',
'posts_per_page' => '10',
'meta_query' => array(
array('key' => 'portfolio_start_date', 'value' => data_to_db2($ricerca_data), 'compare' => '<=', 'type' => 'NUMERIC'),
array('key' => 'portfolio_end_date', 'value' => data_to_db2($ricerca_data), 'compare' => '>=', 'type' => 'NUMERIC')
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$post_count = wp_count_posts();
while ( $the_query->have_posts() ) {
// DO WHAT YOU WANT
}
}
My advice is to use meta_query in $args array

Adding custom fields to the search and results

I'm using the plugin "WP Search Suggest" to suggest in the search field.
Now, the plugin works good, but it only suggest and search titles.
I looked in the plugin and found this:
$query_args = apply_filters(
'wpss_search_query_args',
array(
's' => $s,
'post_status' => 'publish',
'post_type' => 'movie',
),
$s
);
$query = new WP_Query( $query_args );
if ( $query->posts ) {
foreach ( $query->posts as $post ) {
$results[] = $post->post_title;
}
$results = apply_filters(
'wpss_search_results',
$results,
$query
);
echo join( $results, "\n" );
}
and I tried to add support to custom field by adding:
'meta_key' => 'somthing',
'meta_value' => '$s'
but I didn't work, and didn't found a way to 'echo' the results because the '$query->posts' array don't hold the meta keys or values...

Resources