How to get post count of a custom query in wordpress? - wordpress

When I try to get the post count of a custom query in wordpress I get the following error as output.
Warning: array_map(): Argument #2 should be an array in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/class-wp-query.php on line 1918
Warning: implode(): Invalid arguments passed in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/class-wp-query.php on line 1918
0
So below is my function:
if( !function_exists('my_likes') ){
function my_likes() {
global $current_user;
$current_user = get_current_user_id();
// The Query
$args = array(
'meta_key' =>'likes_count',
'orderby' => 'date',
'post__in' => $current_user
);
$obj_name = new WP_Query($args);
$num = $obj_name->post_count;
print $num;
}
add_action('my_likes', 'my_likes');
}

count($obj_name->posts)
This is an inefficient way to count user posts as it gets all the post object. Perhaps just use a raw SQL query

The line 'post__in' => $current_user is incorrect the post__in should be an array so if you want to use it like this you would need to do 'post__in' => array($current_user)
Also from the context i am not sure is you want to use this line at all, if you want to count posts posted by user identified by $current_user then instead of 'post__in' => $current_user you should use 'author' => $current_user
BTW. the line global $current_user; is not needed there at all and overtwites the global $current_user value.
The complete code should look like this i think
function my_likes() {
$current_user = get_current_user_id();
// The Query
$args = array(
'meta_key' =>'likes_count',
'orderby' => 'date',
'post__in' => array($current_user),
// or 'author' => $current_user
);
$obj_name = new WP_Query($args);
$num = $obj_name->post_count;
print $num;
}

Related

WordPress XMLRPC - Search Post by Slug and Update

Is there anyway to search posts by slug through XMLRPC
https://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.getPosts
getPosts() doesn't seem to return using "name"..
$args = array(
'name' => 'my-slug',
'number' => 1
);
$post = $wpClient->getPosts( $args );
Please let me know if there is a workaround for this, I need to search by slug and then update those slugs remotely via XMLRPC. cheers
I ended up using Methods, this may help someone and save time.. paste the following code in functions.php of the domain you are fetching data from
add_filter('xmlrpc_methods', 'clx_xmlrpc_methods');
function clx_xmlrpc_methods($methods) {
$methods['getPostBySlug'] = 'clx_getpost';
return $methods;
}
function clx_getpost($args) {
global $wp_xmlrpc_server;
$slug = $args["slug"];
$pargs = array(
'name' => $slug,
'post_type' => 'post',
'numberposts' => 1
);
$my_posts = get_posts($pargs);
if( $my_posts ) :
return $my_posts; //echo $my_posts[0]->ID;
endif;
}
from your XMLRPC code use the following to get POST array from slug
$args = array(
'slug' => 'your-post-slug'
);
$postArray = $wpClient->callCustomMethod( 'getPostBySlug', $args );

Wordpress Insert post create tne meta key and meta value

I am creating wp_insert_post to create post from json, while creating post i need to create meta values i have tried both add_post_meta and update_post_meta no results Can anybody help
foreach ( $response->data as $single_data ) {
$post_title = $single_data->name;
$video_id = $single_data->uri;
$thumnbnail_url = $single_data->pictures->sizes[4]->link;
if (!post_exists($post_title)) { // Determine if a post exists based on title, content, and date
$post_id = wp_insert_post(array(
'post_type' => 'vimeo_videos',
'post_title' => $post_title,
'post_status' => 'publish',
));
}
$newPostID = wp_insert_post($post_id);
global $post;
add_post_meta( $post->ID, 'vimeo_video_thumnbnail_url_key', $thumnbnail_url, true );
update_post_meta( $newPostID, 'video_url_id', $video_id );
You're using wp_insert_post twice which does not make sense. The first wp_insert_post is correct and will return the $post_id of the created post upon success. However, your
$newPostID = wp_insert_post($post_id);
is totally wrong and will always store 0 as a result in $newPostID, regardless of whether the post existed beforehand or not since $post_id will never contain a valid post array. What you want is to get the ID of the existing post (which post_exists already returns if successful). Change your code like so:
$existingPostID = post_exists($post_title);
if (!$existingPostID) {
$existingPostID = wp_insert_post(array(
'post_type' => 'vimeo_videos',
'post_title' => $post_title,
'post_status' => 'publish',
));
}
if ($existingPostID) {
update_post_meta( $existingPostID, 'video_url_id', $video_id );
}
For insert new post used this syntax:
add_post_meta( int $post_id, string $meta_key, mixed $meta_value, bool $unique = false )

How to get the post ID associated with a Woocommerce Subscription

I am desperately trying to programmatically get the post ID associated with a WooCommerce Subscription object. I am starting from the user id, and trying to request the database using the get_posts function. A call using the get_users_subscriptions works but the objects returned do not include their ID, only the associated order_id or product_id.
$subscriptions = WC_Subscriptions_Manager::get_users_subscriptions(
$current_user->ID
);
$subscription_posts = get_posts( array(
'orderby' => 'date',
'order' => 'ASC',
'numberposts' => 1,
'meta_key' => '_customer_user',
'meta_value' => $current_user->ID,
'post_type' => 'shop_subscription'
) );
The get_post request is sadly returning an empty array. Do you see something wrong in my request ?
Thanks in advance,
I did not find an easy solution so I went with a SQL request based on the order_id contained in the subscription object I get using the call of:
$subscriptions = WC_Subscriptions_Manager::get_users_subscriptions(
$current_user->ID
);
The $wpdb call looks like the following:
$subscription_id = $wpdb->get_var(
"SELECT ID
FROM $wpdb->posts
WHERE `post_type`='shop_subscription'
AND `post_parent`=$first_order->ID
ORDER BY `post_date` ASC
LIMIT 1;"
);
If it helps someone, you're welcome !
I've achieved the same thing with the following code, if you are using the wp rest APIs, it will also add a property to the response:
add_action(
'rest_api_init',
function() {
// add _subscription_id to wc-order response
register_rest_field( 'shop_order', '_subscription_id', [
'get_callback' => function ($order) {
$subscriptionIds = wcs_get_subscriptions_for_order( $order['id'] );
foreach( $subscriptionIds as $subscriptionId => $subscription )
if($subscription->order->id == $order['id']) break;
foreach( $order['meta_data'] as $meta )
if ($meta->key === '_subscription_renewal') {
$metaSubscriptionId = $meta->value; break;
}
return $subscriptionId ?: (int) $metaSubscriptionId;
},
'update_callback' => null,
'schema' => null,
]);
}
);

Does "Advanced Custom Fields" taxonomy field support user pages?

I have a "taxonomy" custom field for the user pages. I want to build a query filtered by this field. It works with normal querys but not with user-querys, am i doing something wrong?
<?php
$args = array(
'key' => 'fruits',
'value' => 'apple'
);
// The Query
$user_query = new WP_User_Query( $args );
// User Loop
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
echo $user->display_name;
}
} else {
echo 'No users found.';
}
?>
Try get_users instead:
$users = get_users(array(
'meta_key' => 'fruits',
'meta_value' => 'apple'
));
var_export($users);
Wordpress codex: get_users()
Edit:
After a bit of research it turns out that get_users() is only a wrapper for WP_user_query, so switching to this function will make no difference.
However... did you notice that in my answer (and vrajesh') we have substituted your key with meta_key, and value with meta_value ... They are definitely defined in the WP_User_Query class, so I would be surprised if they didn't have any meaning.
If by chance you are using your original $args (which I guess does not actually refer to fruits and apples), then that may well be the explanation you are getting nothing.
try this:
$args = array( 'meta_key' => 'fruits', 'meta_value' => 'apple','compare' => '=');
Use WP_Query instead of WP_User_Query. WP_User_Query is used to retrieve data from user and usermeta table. And according to my understanding your are retrieving data from posts and postmeta table.
Class Reference/WP User Query and
Class Reference/WP Query
UPDATED:
Try this
<?php
$args = array(
'meta_query' => array(
'key' => 'fruits',
'value' => 'apple',
'compare' => '='
)
);
// The Query
$user_query = new WP_User_Query( $args );
// User Loop
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
echo $user->display_name;
}
} else {
echo 'No users found.';
}
?>

exclude a post from wp_query loop wordpress

I show my last post in a page with this code:
$query1 = new WP_Query();
$query1->the_post();
and it further with:
$id = $query->ID;
to retrive last post ID
so I wrote a new wp_query and I want to exclue that ID from the results:
I wrote this but it don't work:
$query2-> new WP_Query('p=-$id');
what's the problem?
You haven't excluded anything. Read the Codex. p= includes posts. It does not exclude them. What you need is post__not_in
$query2-> new WP_Query(array('post__not_in' = array($id)));
My code is works fine:
$ID =array('1,2,3,4,5');
$news = new WP_Query(array('
'post_type' => 'post',
'showposts' =>3,
'order' => 'DESC',
'post__not_in' => $ID
));
if ( $news->have_posts() ) :
echo '<div>';
while ( $news->have_posts() ) : $news->the_post(); ?>`
//Your code here

Resources