I'm trying to display some snippets (loaded via get_template_part()) based on a custom taxonomy terms assigned to a post.
So far I can get taxonomy terms assigned to the post with
$term_list = wp_get_post_terms($post->ID, 'sidebar_snippets', array("fields" => "all"));
print_r($term_list);
Which produces an array of objects like that:
(
[0] => WP_Term Object
(
[term_id] => 11
[name] => Future Events
[slug] => future_events
[term_group] => 0
[term_taxonomy_id] => 11
[taxonomy] => sidebar_snippets
[description] =>
[parent] => 0
[count] => 2
[filter] => raw
)
)
I was thinking of iterating over an array of assigned terms and load the appropriate snippets. The snippets' names are identical with the 'slug' of taxonomy term.
$term_list = wp_get_post_terms($post->ID, 'sidebar_modules', array("fields" => "all"));
print_r($term_list); // works fine - outputs three terms (like above)
foreach($term_list as $term) {
echo $term['slug']; // does not out put anything.
get_template_part( 'modules/' . $term['slug] . '.php' );
}
I have two problems. One that it doesn't not even output the $term[slug]. Secondly, how would I add some validation, eg. check if the file exists first before trying to get_template_part?
Thank you
You are trying to access object value as array so it not echo the value. Use the below code for echo correctly.
foreach($term_list as $key => $term) {
$term_slug = $term->slug; // does not out put anything.
get_template_part( 'modules/'.$term_slug.'.php' );
}
For more help see this link : Click Here
Thanks
Related
I am building an e-commerce website and I have installed the following plugin (Customer reviews for Commerce - https://wordpress.org/plugins/customer-reviews-woocommerce/) for Reviews and Ratings of Orders once user completes the order process.
However, the nature of the products we deal with (like fabrics, dresses, sarees etc.) will run out of stock and the same product will not be available again to procure. So, I would want to display the reviews and ratings of old orders using the 'tags' of the products which the order had (For this reason, I would like to have review at order line item). Further, the new product page should fetch the reviews and ratings using it's own tags from old orders which had the same tags.
Any guidance would be helpful in this matter!
To approach this problem, first thing to do is to get all tags associated with a given product into an array. And then, WP_Comments_Query needs to be queried with the array of product ids generated in the first step.
Here is a snippet with the above mentioned approach.
function get_reviews_by_tags(){
global $product;
$productid = $product->get_id();
// get all product_tags of the current product in an array
$current_tags = get_the_terms( $productid, 'product_tag' );
//only start if we have some tags
if ( $current_tags && ! is_wp_error( $current_tags ) ) {
//get all related product ids mapped by tags array we created earlier
$relatedproductids_by_tags = get_posts( array(
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'publish',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_tag',
'field' => 'term_id',
'terms' => $current_tags,
'operator' => 'IN'
)
),
));
// create a wp comment query object as wc uses comments for reviews
$reviews_args = array(
'post__in' => $relatedproductids_by_tags
);
$reviews_query = new WP_Comment_Query;
$reviews = $reviews_query->query( $reviews_args );
if ( !empty( $reviews ) ) {
foreach ( $reviews as $review ) {
echo '<p>' . $review->comment_content . '</p>';
}
} else {
echo 'No reviews found.';
}
}
add_action( 'woocommerce_after_single_product_summary', 'get_reviews_by_tags', 10, 2 );
}
The above code does not consider any modifications being made by the plugin you mentioned in your question. Also, please note that this code is for fetching and displaying reviews as mentioned in your question. This is not for creating reviews.
I' making my own shortcode function and while the call of the shortcode works, and my page query within returns results - it never uses any settings but the defaults as if $att is null.
function test_shortcode( $atts ) {
$filter = shortcode_atts(
array(
'type' => 'major',
'sort' => 'name',
'size' => 'large',
'links' => 'yes',
),
$atts,
'customshortcode'
);
echo 'ATTS:';
print_r($atts);
echo'FILTER';
print_r($filter);
//code to query posts removed
}
add_shortcode( 'customshortcode', 'test_shortcode' );
In the post I can then add..
[customshortcode type:"other" size:"small" sort:"rand" links:"no"]
To see the result
ATTS
Array
(
[0] => type:"other"
[1] => size:"small"
[2] => sort:"rand"
[3] => links:"no"
)
FILTER
Array
(
[type] => major
[sort] => name
[size] => large
[links] => yes
)
and I can see the $atts values are received in the function but the $filter is not updated. I'm expecting both arrays to be the same at the point they are being printed out. As far as I can tell I'm following the coxed formatting here https://codex.wordpress.org/Function_Reference/shortcode_atts
You are passing attributes in the wrong way.
It should use = instead of :.
Please go through https://developer.wordpress.org/plugins/shortcodes/shortcodes-with-parameters/ to know more about shortcode with parameters.
Try with [customshortcode type="other" size="small" sort="rand" links="no"]
I use wordpress standard with the plugins "Advanced custom fields" and "custom_post_type ui". I created a post_type called deals and added some custom fields with it.
What I need to do now, is filter the results when accessing the rest api like this:
http://localhost:8000/wp-json/wp/v2/deals
Actually I only need the acf part of it. I dont care about the rest.
[{"id":29,"date":"2019-04-12T12:34:14","date_gmt":"2019-04-
12T12:34:14","guid":{"rendered":"http:\/\/localhost:8000\/?
post_type=deals&p=29"},"modified":"2019-04-
12T12:34:14","modified_gmt":"2019-04-12T12:34:14",
"slug":"test-title","status":"publish","type":"deals",
"link":"http:\/\/localhost:8000\/deal s\/test- title\/","template":"",
"meta":[],"tax-deals":[],"acf":{"title":"Title for Deals
Post","description":"","image":false,"date_start":"01.01.1970",
"date_end":"01.01.1970","category":"Kleidung"},"_links":{"self":
[{"href":"http:\/\/localhost:8000\/wp-json\/wp\/v2\/deals\/29"}],
"collection":[{"href":"http:\/\/localhost:8000\/wp-
json\/wp\/v2\/deals"}],"about":[{"href":"http:\/\/localhost:8000\/wp-
json\/wp\/v2\/types\/deals"}],"wp:attachment":
[{"href":"http:\/\/localhost:8000\/wp-json\/wp\/v2\/media?
parent=29"}],"wp:term":[{"taxonomy":"tax_deals","embeddable":true,
"href":"http:\/\/localhost:8000\/wp-json\/wp\/v2\/tax-deals?
post=29"}],"curies":
[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},
I have already tried using
http://localhost:8000/wp-json/wp/v2/deals?search=id
to get the id or something, but response is empty.
Also this didnt work:
http://localhost:8000/wp-json/wp/v2/deals?id=28
Again empty response.
To summarize: I need to filter my custom post type on my custom fields by the "acf" attribute shown in my response json. How does it work?
EDIT: I already installed "WP REST Filter" but still dont know how to do it.
I suggest you to create a new API where you can customize the output. Take advantage of wordpress function register_rest_route() using this you can create an API from CPT and ACF in one ajax url. And you do not need to install anything.
Check how I get my instructor CPT and mycheckbox ACF.
// your ajaxurl will be: http://localhost/yoursite/wp-json/custom/v2/instructor/
add_action( 'rest_api_init', function () {
register_rest_route( 'custom/v2', '/instructor', array(
'methods' => 'GET',
'callback' => 'instructor_json_query',
));
});
// the callback function
function instructor_json_query(){
// args to get the instructor
$args = array(
'post_type' => 'instructor',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'mycheckbox', // your acf key
'compare' => '=',
'value' => '1' // your acf value
)
)
);
$posts = get_posts($args);
// check if $post is empty
if ( empty( $posts ) ) {
return null;
}
// Store data inside $ins_data
$ins_data = array();
$i = 0;
foreach ( $posts as $post ) {
$ins_data[] = array( // you can ad anything here and as many as you want
'id' => $posts[$i]->ID,
'slug' => $posts[$i]->post_name,
'name' => $posts[$i]->post_title,
'imgurl' => get_the_post_thumbnail_url( $posts[$i]->ID, 'medium' ),
);
$i++;
}
// Returned Data
return $ins_data;
}
Then, you can use the link: http://localhost/yoursite/wp-json/custom/v2/instructor/ in your ajax url.
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.
There are tutorials that explain how to limit a search to a specific category.
My question is, is there a way to configure wordpress' search to, within a custom post type, search for a custom field value.
So for example, if I search for "hello", the results would come up with posts that have a certain custom field equal to "hello". The certain post would also be a certain custom post type.
Any help is appreciated.
To filter search by custom post type use:
<?php query_posts($query_string . '&post_type=custom-post-type-name' ); ?>
before the loop.. then within the loop add a condition similar to this
<?php if ($meta_data[ 'meta-name' ] == 'hello') {
//do something
} ?>
I think here is what you are looking for:
key is the custom field.
value is the value you are looking for
and compare is the operator you want to use.
you can also use LIKE if you want.
// WP_Query arguments
$args = array (
'post_type' => 'vendors',
'post_status' => 'published',
'meta_query' => array(
array(
'key' => 'state',
'value' => 'Misissipi',
'compare' => '=',
),
),
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();