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.';
}
?>
Related
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 );
My custom post type "references" has a custom field called "references_count". It has a numeric value.
I have an custom taxonomy called "country" with a custom field called "country_count" for the terms.
Background:
The custom post type "references" saves cities with a number of clients in this city. This value is saved in the field "references_count". In the custom taxonomy there are countries. For each country, there is a total number of references.
Example:
In the city of "Berlin" there are 3 clients. In the city of "Munich" there are 2 clients. The taxonomy term "Germany" includes the sum of all cities in this country. So the value of "country_count" in this example for the taxonomy term "Germany" is 5, being the sum of the references of each city.
I wrote this code which is working, if I'm saving each individual taxonomy term.
add_action( 'edited_country', 'update_counter_for_countries', 10, 2 );
function update_counter_for_countries( $term_id ) {
// Get posts with term
$args = array(
'post_type' => 'reference',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'country',
'field' => 'term_id',
'terms' => $term_id
)
)
);
$the_query = new WP_Query( $args );
// sum values in posts
$sumTerm = 0;
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$number = get_field( 'references_count', get_the_ID() );
$sumTerm = $sumTerm + $number;
}
}
wp_reset_postdata();
// update field in term
update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id );
}
Problem:
I have more than 100 countries (taxonomy terms), so I have to save each term individually to get things going.
What I am looking for: Is there a way to update / save all custom taxonomy terms at once, so I don't have to update each term seperately? I checked out a lot of plugins, but couldn't find any plugin which gives the possibility of "bulk edit" or "bulk save" taxonomy terms. I would prefer a solution without plugin if possible. I am very grateful for any hint, thank you very much.
You can use this code to update all terms in one go.
Just make sure to backup your database in case needed.
This code will loop through all the terms and will only run once. after that you can remove this code.
Just to make this code run only on your IP, change 111.111.111.111 to your IP ADDRESS.
if($_SERVER["REMOTE_ADDR"]=='111.111.111.111'){
//run only my ip
add_action("init","update_all_terms_in_one_go");
}
function update_all_terms_in_one_go(){
session_start();
if(isset($_SESSION['all_terms_updated']) && $_SESSION['all_terms_updated'] == "done"){
return;
}
$taxonomy = "country";
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => false,
]);
foreach ($terms as $term) {
update_counter_for_countries( $term->term_id );
}
$_SESSION['all_terms_updated'] = "done";
echo "ALL TAXONOMY TERMS UPDATED";
die();
}
function update_counter_for_countries( $term_id ) {
// Get posts with term
$args = array(
'post_type' => 'reference',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'country',
'field' => 'term_id',
'terms' => $term_id
)
)
);
$the_query = new WP_Query( $args );
// sum values in posts
$sumTerm = 0;
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$number = get_field( 'references_count', get_the_ID() );
$sumTerm = $sumTerm + $number;
}
}
wp_reset_postdata();
// update field in term
update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id );
}
I wanted to have a neat admin page with a button to bulk update all my taxonomy terms. The process should work using AJAX so it can take a while without confusing the user. There should be status messages.
So in the first step I added a new admin page to the wordpress backend.
add_action( 'admin_menu', array( $this, 'my_admin_page' ) );
function my_admin_page() {
add_menu_page(
__('Bulk Terms'), // page title
__('Bulk Terms'), // menu title
'manage_options', // user capabilities
'options-page', // menu slug
'my_output_function', // output function
'dashicons-admin-generic', // menu icon
77 // menu position
);
}
In the output function I put a form with a button to bulk update terms. And some status messages.
function my_output_function() {
echo '<div class="wrap">';
echo '<form action="admin.php?page=options-page" method="post">';
wp_nonce_field( 'ajax_validation', 'nonce' ); // security feature
submit_button('Update Terms', 'primary', 'submitOptions', false);
echo '</form>';
echo '<div id="processing" style="display:none;">Please wait</div>';
echo '<div id="error" style="display:none;">Something went wrong</div>';
echo '<div id="success" style="display:none;">Done!</div>';
echo '</div>';
}
In the second step I had to enqueue script file for ajax calls:
add_action( 'admin_enqueue_scripts', 'my_ajax_scripts' );
function my_ajax_scripts() {
// Check if on specific admin page
global $pagenow;
if (( $pagenow == 'admin.php' ) && ($_GET['page'] == 'options-page')):
wp_enqueue_script( 'ajaxcalls', plugin_dir_url( __FILE__ ).'/js/ajax-calls.js', array('jquery'), '1.0.0', true );
wp_localize_script( 'ajaxcalls', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_validation' )
) );
endif;
}
And create the function to bulk update all my taxnomy terms:
function options_page_action() {
$taxonomy = "country";
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => false,
]);
foreach ($terms as $term) {
$term_id = $term->term_id;
// Get posts with term
$args = array(
'post_type' => 'reference',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'country',
'field' => 'term_id',
'terms' => $term_id
)
)
);
$the_query = new WP_Query( $args );
// sum values in posts
$sumTerm = 0;
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$number = get_field( 'references_count', get_the_ID() );
$sumTerm = $sumTerm + $number;
}
}
wp_reset_postdata();
// update field in term
update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id );
}
$result = array( 'status' => 'success' ); // create response
wp_send_json_success( $result ); // send response
wp_die(); // close ajax request
}
As the third step, in my ajax_calls.js file I take the click event to call the function for updating the taxonomy terms using ajax.
$( '#submitOptions' ).click( function(event) {
event.preventDefault();
$('#submitOptions').css('cssText','display:none;');
$('#processing').css('cssText','display: block;');
$.ajax({
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'options_page_action',
nonce: ajax_object.ajaxnonce
},
success: function( response ) {
if( response['data']['status'] == 'success' ) {
$('#processing').css('cssText','display:none;');
$('#success').css('cssText','display:block;');
}
},
error: function() {
$('#processing').css('cssText','display:none;');
$('#error').css('cssText','display:block;');
}
});
});
There are messages indicating that the function is running and it show messages when it's done or has an error. This way the user will always know what's going on when bulk updating terms.
I have a custom post type of 'location'. I then have children pages for each of the pages for that cpt. so it looks something like this, "www.example.com/location/location-name/child-page/", each child page is using a post template of "location-product-services.php". So what I am trying to do is exclude from the search results the children of this cpt.
I am trying to do it by checking the meta data to see if it is using that template. I just cant seem to get it working. Any help would be great.
This is what I currently have -
// Exclude local product and services pages from search result.
function location_subpages_exclude_search( $query ) {
if ( is_search() && !is_admin()) {
$query->set('meta_query',
array(
'key' => '_wp_page_template',
'value' => 'location-product-services.php',
'compare' => '!='
)
);
}
}
add_action('pre_get_posts', 'location_subpages_exclude_search');
Thanks in advance.
First, I pretty much exclusively use the Relevanssi plugin any time I want to modify search. But to search programmatically, I think this is what you're after:
$taxonomy = 'location';
$terms = get_terms($taxonomy, array( 'parent' => 0, 'search' => $query ) );
if ( $terms && !is_wp_error( $terms ) ) :
?>
<ul>
<?php foreach ( $terms as $term ) { ?>
<li><?php echo $term->name; ?></li>
<?php } ?>
</ul>
<?php endif;?>
Use the function get_terms to search your CPT, the 'search' is your $query (you might consider wrapping the search string with the SQL wildcard '%') and 'parent'=>0 returns only the top level.
I figured it out.
First I got all parent pages of my post type, used get_pages() grab them all.
Looped through each of the parent pages and ran another get_pages() for children of that parent.
function SearchFilter($query) {
if ($query->is_search) {
$args = array(
'hierarchical' => 0,
'post_type' => 'location',
'parent' => 0, //returns all top level pages
'post_per_page' => -1
);
$parents = get_pages($args);
$excludes = array();
foreach($parents as $parent) :
$args = array(
'post_type' => 'location',
'child_of' => $parent->ID,
'post_per_page' => -1
);
$children = get_pages($args);
foreach($children as $child):
array_push($excludes, $child->ID);
endforeach;
endforeach;
$query->set('post__not_in', $excludes);
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
I'm working on a new project where registered users can select multiple careers in the User Profile page in wordpress Admin. I have been able to add the check boxes of different careers to the User profile page which registered users can check/select.
At the frontend, I created a page for each of the careers. I want a scenerio whereby if one should go to page named "Programmer" for example, one would be shown all the authors that check "Programmer" in their profile. The authors info like avatar, name and links to all posts would be shown in a loop
I don't know how to go about it. Hoping you guys here can assist with this.
-------------------------------EDITED---------------------------
With the help provided by #AustinWinstanley thus far, here is my code
$user_query = new WP_User_Query( array( 'meta_key' => 'career', 'meta_value' => 'programmer' ) );
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
echo '<p>' . $user->display_name . '</p>';
}
} else {
echo 'No users found.';
}
With the above query, any author whose career field's value is programmer is listed. The above code is suitable if the value field for Career is an input field. I don't intend to make career's value to be an input field, rather I want it to be checkboxes where authors can check multiple values.
Since it's not going to be an input field, but rather checkboxes, how do I edit this line to reflect what I want?
$user_query = new WP_User_Query( array( 'meta_key' => 'career', 'meta_value' => 'programmer' ) );
You probably want to query users by meta data. Something like this:
// Set this value by whatever you're searching for
$career = 'programmer';
$args = array(
'meta_query' => array(
'relation' => 'AND',
array(
array(
'key' => 'career',
'value' => $career,
'compare' => 'LIKE'
// Or 'compare' => '='
)
)
)
);
$user_query = new WP_User_Query( $args );
$result = $wp_user_query->get_results();
Edit:
For the front end form:
<form method='post'>
<input name="careers[]" type="checkbox" value="programmer"> Programmer
<input name="careers[]" type="checkbox" value="accountant"> Accountant
<input name="careers[]" type="checkbox" value="manager"> Manager
<button name="career-search">Search</button>
</form>
In your plugin or function/includes:
function careers_postback( $query ) {
if( $query->is_main_query() && isset( $_POST['career-search'] ) ) {
$careers = $_POST['careers']
$meta_query = array();
foreach( $careers as $career ) {
$meta_query[] = array(
'relation' => 'AND',
array(
array(
'key' => 'career',
'value' => $career,
'compare' => '='
)
)
);
}
$args = array(
'meta_query' => $meta_query
);
$user_query = new WP_User_Query( $args );
$result = $wp_user_query->get_results();
set_query_var( 'search-career-results', $result );
// Here you would include your search template and call exit
// In your template, use `get_query_var( 'search-career-results')
// Then check if there are results and list them if there are.
}
}
add_filter( 'pre_get_posts', 'careers_postback' );
This is in general. I haven't fully tested it because I'm not typing it in an editor. But this is the full solution to check boxes and get users by their meta data using the data. If this doesn't work in general, then you are doing something you aren't revealing. Like not saving careers to user meta data.
It appears as tho the search functionality for WooCommerce products does not check "product_tag" taxonomy terms, nor SKU field? I added the SKUs as product tags to their respective products, but it still returns nothing when I search for the SKU.... How do I make the search functionality check product_tag terms? I have tried many many many things from adding tax_query to pre_get_post filter, to a whole new WP_Query loop, it just fails to search product_tags for some reason....so what is the point in a Product Tag???
I've tried the code from woo and others to search SKU with no results. However, the plugin search-everything, download from repository, does the job.
I got the solution to search the products by SKU code.
It is too simple just paste the following code in function.php and then you can see the changes in search results.
function search_by_id_only( $search, &$query_vars ) {
global $wpdb, $pagenow;
if ( 'edit.php' == $pagenow || empty($search) ) {
return $search;
}
$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
'meta_query' => array(
array(
'key' => '_sku',
'value' => $query_vars->query['s'],
'compare' => 'LIKE'
)
)
);
$posts = get_posts( $args );
if ( empty( $posts ) ) return $search;
$get_post_ids = array();
foreach($posts as $post){
$get_post_ids[] = $post->ID;
}
if ( sizeof( $get_post_ids ) > 0 ) {
$search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $get_post_ids ) . ")) OR (", $search);
}
return $search;
}
add_filter( 'posts_search', 'search_by_id_only', 999, 2 );