I have added a custom taxonomy to Users - user categories.
Using the code below, I am able to output the custom taxonomies in each edit-user profile page:
function show_user_category( $user ) {
//get the terms that the user is assigned to
$assigned_terms = wp_get_object_terms( $user->ID, 'user_category' );
$assigned_term_ids = array();
foreach( $assigned_terms as $term ) {
$assigned_term_ids[] = $term->term_id;
}
//get all the terms we have
$user_cats = get_terms( 'user_category', array('hide_empty'=>false) );
echo "<h3>User Category</h3>";
//list the terms as checkbox, make sure the assigned terms are checked
foreach( $user_cats as $cat ) { ?>
<input type="checkbox" id="user-category-<?php echo $cat->term_id ?>" <?php if(in_array( $cat->term_id, $assigned_term_ids )) echo 'checked=checked';?> name="user_category[]" value="<?php echo $cat->term_id;?>"/>
<?php
echo '<label for="user-category-'.$cat->term_id.'">'.$cat->name.'</label>';
echo '<br />';
}
}
The code above simply displays a list of checkboxes, ordered by term_id.
Of course, I want to display them in the same way that custom taxonomy terms would be displayed in a custom post type (a scrollable list of checkboxes, with child terms indented and underneath their parent term). The code above does not display the terms in order of parents/children.
Is there a WP function I can pass my taxonomy & terms to, to create what I described in the paragraph above? Or do I have to do it manually?
Thanks
Short answer:
Yes, there are. They are called post_categories_meta_box() and post_tags_meta_box(), depending on the type of taxonomy you are using.
Long answer:
This is the sort of question that can be answered by inspecting the WP core code.
Here's the walk-through on how I did it to answer this question:
Editing a page in admin results in a url of wp-admin/post.php. So, inspect that file (post.php).
A quick search in that file for "tax" results in nothing, so we can at least look at the case 'edit' section, because we know we're doing an edit. And we can see it includes a file edit-form-advanced.php.
So, inspect that file (edit-form-advanced.php)
A quick search for "tax" gets into an area that looks promising.
Here we see they call get_taxonomy, and then that get_taxonomy object that is returned has a callback called meta_box_cb - so do a cross-file search for that. We find several instances, but the instance in taxonomy.php is the most promising (because of the file name), so lets look there.
It appears (around line 430 of taxonomy.php) that there's a pair of callback functions - post_categories_meta_box and post_tags_meta_box that WP core is using. Let's check them out - do a cross-file search for function post_categories_meta_box, and we find both of these functions exist in the file meta-boxes.php. The comments for the functions are excellent, and tell us what you are asking: "Display post categories form fields".
Armed with this information, we can ask Google, and we find the WP documentation for the functions:
post_categories_meta_box
and
post_tags_meta_box
Related
Goal/Information
I'm trying to set up a custom search field and custom search results page to display one category of pages. I need these results on a separate, custom search results page so I can customize how the results are displayed without affecting the default search.
For context, I'm setting up a gallery where the user can search for keywords and relevant pages will be displayed as a thumbnail grid, with each thumbnail linking to a page containing more information on the image.
Each page, containing the image and information, is set up as a page (not post) under the category images.
I'm not sure this is relevant, but in a previous project I've set the default search to exclude images pages with the following code in my functions.php (category ID is 30). I've tried removing this code and it didn't affect my problem described below.
/* Exclude a Category from Search Results */
add_filter( 'pre_get_posts' , 'search_exc_cats' );
function search_exc_cats( $query ) {
if( $query->is_admin )
return $query;
if( $query->is_search ) {
$query->set( 'category__not_in' , array( 30 ) ); // Cat ID
}
return $query;
}
What I've Tried
I'm still learning php and have spent many hours on this to no avail. Most recently I tried tweaking some code from this similar question.
My resultant custom search form looks like this:
<form class="search-form" action="<?php echo home_url( '/' ); ?>" method="get">
<input name="s" type="text" placeholder="Search Images" />
<input name="post_type" type="hidden" value="page" />
<input name="category_name" type="hidden" value="images" />
<input alt="Search" type="submit" value="Search" />
</form>
I've added the following code to the top of my search.php to attempt to redirect to another results page, in this case search-page.php, if the post type has been specified:
<?php
// store the post type from the URL string
$post_type = $_GET['post_type'];
// check to see if there was a post type in the
// URL string and if a results template for that
// post type actually exists
if ( isset( $post_type ) && locate_template( 'search-' . $post_type . '.php' ) ) {
// if so, load that template
get_template_part( 'search', $post_type );
// and then exit out
exit;
}
?>
Note: I took this directly from the similar question linked above.
I've duplicated search.php into search-page.php, removing the code above from the latter.
Problem
Now let's do a search in the custom form above for "marble" (a term featured in one of the image pages). The URL looks right (http://example.com/%3C?s=marble&post_type=page&category_name=images), but I get a 404. In addition, normal searches (those not in the custom form) now take me to a white page – not even a 404. When I remove the above code from functions.php, the default search works properly. (Custom search still 404s.)
Other Attempts
I've also read this guide from Smashing Magazine a few times – Building An Advanced WordPress Search With WP_Query – but can't quite pick out the information relevant to me.
I've tried a couple dozen other guides and questions, but most of them deal with searching for a specific post type alone (and not a category) or searching from a radio-button selection of categories. I haven't been able to scrape any working solutions from them.
Are there any tweaks to what I've tried – or completely different solutions altogether – that will help achieve the desired effect? Specifically, how to create a custom search form for one type of page category, leading to a customizable, separate search results page (independent from the default search results page).
Thanks in advance.
I want to hook into the save_post function, find out what category the post is in, and then assign a different page template for posts in each category. I've tried about 30 different versions of this with no luck. Will someone please help point me in the right direction?
add_action( 'save_post', 'assign_custom_template' );
function assign_custom_template($post_id) {
$category = get_the_category($post_id);
$cat_id = $category->cat_ID;
if( $cat_id == 1 ) {
update_post_meta($post_id, "_wp_page_template", "template1.php");
}
if( $cat_id == 2 ) {
update_post_meta($post_id, "_wp_page_template", "template2.php");
}
}
You just need to create category-1.php which rendered as template1.php and category-2.php which rendered as template2.php in your theme root.
See template hierarchy for more info.
I tried to emulate the official WP hierarchy scheme among my posts & custom post types, but it just wasn't happening. I ended up using Custom Post Types so that I could assign templates to both the "list" pages and the "individual" pages. And then I wrote some javascript that looks for the post-type string in the URL, and if it's detected, it adds the current_page_parent/ancestor classes to the appropriate menu items. Not perfect or totally future-proof, but it gets the job done.
If someone comes up with a better solution, please post it!
This question is based on an unanswered question in Wordpress Development which has not gotten a solid answer.
I have a wordpress website which lists hotels. the url for a single hotel looks like:
/hotels/the-marriot-hotel
I also have a custom taxonomy for Locations, which allows me to browse the hotels in various locations, which works fine, the urls are like:
/Locations/Liverpool
For URL's like /hotels/* I would like to use a custom template, which I have done already and works fine.
The Problem
I also want to be able to drilldown the Locations taxonomy creating a breadcrumb type URL and also use a different template for the hotel page.
For Example, if a user is browsing /Locations/Liverpool and clicks the Marriot Hotel I would like it to click through to /Locations/Liverpool/the-marriot-hotel instead of /hotels/the-marriot-hotel and also use a slightly different template, which can also load a different sidebar and recommend other hotels in the area specific to the location slug in the URL
So basically I want two routes to a single post and a different template used based on the route used.
How would I go about implementing this?
What have I tried?
I've tried adding a new page and using a rewrite rule to point to it to be the locations hotel page.
I've tried adding a slug on the end of the /Locations/{location-slug} url and reading this in the page template and loading the hotel post instead of the list it doesn't seem to be working but also feels like a terrible hack anyway
An idea that I've had is to add a rewrite to the hotels/{slug} page and using code to detect the URL used and switch templates dynamically but I'm not sure this is the best approach
I have managed to get this working using the second method mentioned above (adding a rewrite to the locations landing page and checking for a query_var).
I will post the code below that I used but although this works and seems to be working very well, It does not feel like the best way of doing it. If someone know of a better way of doing this please post the answer.
I used this online post for reference.
Note: The listing page shows the list of hotels in the taxonomy in a side column down the side and shows the currently selected or a random one in the main content area. Which will explain how I am using the loop below.
function prefix_locations_rewrite_rule() {
add_rewrite_rule( 'Locations/([^/]+)/([^/]+)', 'index.php?locations=$matches[1]&hotel=$matches[2]', 'top' );
}
function prefix_register_query_var( $vars ) {
$vars[] = 'hotel';
return $vars;
}
function prefix_url_rewrite_templates() {
if ( get_query_var( 'hotel' ) && is_singular( 'hotel' ) ) {
add_filter( 'template_include', function() {
return get_template_directory() . '/taxonomy-locations.php';
});
}
}
add_action( 'template_redirect', 'prefix_url_rewrite_templates' );
add_filter( 'query_vars', 'prefix_register_query_var' );
add_action( 'init', 'prefix_locations_rewrite_rule' );
In my template file for the hotels landing page:
$hotelSlug = get_query_var( 'hotel', false);
if ( have_posts() ) {
while (have_posts()) : the_post();
if ($post->post_name == $hotelSlug) {
break;
}
endwhile;
}
This bit of code will iterate over the posts and if the hotel slug matches the query var it will break there so that the current post is the one we wanted.
We could just use a query here but as I already have a list of posts within the taxonomy I thought I'd just iterate over it. Below this I check to see if a specific hotel has been selected otherwise I show a random one from the list.
I am still to add additional logic and error handling to this code, I hope it helps someone with a similar issue
I'm working on a drupal site, and I need to have an information page for taxonomy data.
The taxonomy data has some extra fields that are displayed, including a custom link.
The default taxonomy page does not allow a custom link, and it will show the content assiociated to the term, I don't want that.
I made a module that outputs a block, and I'm basicly using this code
$term = taxonomy_term_load($termId);
This works fine, but I can't get the translated version of the taxonomy! I'm using the i18n module.
How can I get the localized version of the taxonomy?
Thanks in advance,
Jorik
The langcode parameter of taxonomy_term_view() is used to filter by the language of associated nodes. it is (unfortunately?) not related to the language of the term itself.
You can get the i18n-localized term with
$term = taxonomy_term_load($tid);
if (module_exists('i18n_taxonomy')) {
module_load_include('inc', 'i18n', 'i18n_taxonomy.pages');
$term = i18n_taxonomy_localize_terms($term);
}
print render(taxonomy_term_view($term, 'full'), $language->language);
You need to run your term object through taxonomy_term_view(), that will build the view for you with a particular language code. You can get the 'current' language for the page using the global $language object:
global $language;
$term = taxonomy_term_load($termId);
$view = taxonomy_term_view($term, 'full', $language->language);
$html_output = render($view);
Just a tip, as of writing the Views module doesn't fully support localized terms, as the default taxonomy pages do. You could check out http://drupal.org/project/i18nviews
In wordpress (ideally, with out the use of a plug-in) on a tag page I would like to show the number of posts that are tagged with the current tag.
Example:
There are 8 posts with the tag "baseball"
when you are on the tag page for baseball it says, "There are 8 posts about baseball"
It should dynamically know which tag page your on, get the count and print it. I have found several options for statically entering the tag name or ID and returning the count but my attempts to get them to work dynamically have been unsucessful.
This is what I was working with:
$taxonomy = "post_tag"; // can be category, post_tag, or custom taxonomy name
// Using Term Name
$term_name = single_cat_title;
$term = get_term_by('name', $term_name, $taxonomy);
// Fetch the count
echo $term->count;
Any help would be greatly appreciated!
You can just print the found_posts property of the WP Query object
echo $wp_query->found_posts;
Open the file in your template named "tag.php" and enter the desired code in it.
Here is another possible solution from WP Recipes. They were kind enough to post this the day after I got an answer here. :)
<?php
$feat_loop = new WP_Query( 'showposts=12&category_name=featured' );
echo "Query returned ".$feat_loop->post_count." posts.";
?>
It has different application but still very useful!
http://www.wprecipes.com/get-how-many-posts-are-returned-by-a-custom-loop?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+Wprecipes+%28WpRecipes.com%3A+Daily+recipes+to+cook+with+WordPress%29