I'm trying to display an image in a custom field on child category archive pages.
The current setup is:
<?php
$term_id = get_queried_object()->term_id;
$post_id = 'product_cat_'.$term_id;
$custom_field = get_field('brand_background', $post_id);
?>
<div id="brandHeader" class="brand-header-logo" style="background-image: url('<?php the_field('brand_background', $post_id); ?>');">
This obviously gets the 'background image' field from the category archive it's currently on.
If the category is a child category I want to be able to pull the 'background image' from the parent category. I've tried a few things but doesn't seem to be working - can anyone help?
You could use the get_ancestors function to get the parent id and use that id to get your field:
get_ancestors
So let's say your categories looks like this:
-Parent (id = 24)
--Child (id = 42)
$term_id = get_queried_object()->term_id;
$term_ancestor_ids = get_ancestors($term_id, 'product_cat');
// if you do a print_r on $term_ancestor_ids
// you'll see this:
// Array ( [0] => 24 )
$post_id = 'product_cat_'.$term_ancestor_ids[0];
$custom_field = get_field('brand_background', $post_id);
Tested and works, let me know if you were able to get it to work too!
Related
How to retrieve the category description when using a filter like wp Gridbuilder?
I created a sort filter for the categories, when clicking on a category the url looks something like this: domain.com/music/?_categories=8-bit-chiptune
Normally using <?php echo category_description( $category_id ); ?> would work on the archive category page but whe using a filter there is no category page.
Thanks
You can try the below code & process as your need.
<?php
$cat_slug = $_GET['_categories'];
$idObj = get_category_by_slug( $cat_slug );
if ( $idObj instanceof WP_Term ) {
echo $id = $idObj->description;
}
Feel free to query question about it.
I'm making my first theme and everything is progressing real fast thanks to all the assistance offered by The Loop and WooCommerce's SDK. Then today I spent an entire day failing to do something as simple as showing an image... After an entire day of struggling the only things I managed to learn is that WP seems to offer NO means for fetching a category's image and MANY people have asked this question for many years and STILL I can't find a way to ACTUALLY do it...
:(
What I want to do is create a slider above my store that shows the images of a curated selection of shop categories. I want to be able to enter a list of term names and based on that my function should generate links to the product categories in the form of the category's image.
Sounds simple... turns out, it's nowhere near CLOSE to simple... Before you go off and mark this as a duplicate question, let me explain why I am asking it...
Some of the solutions I have found require that I know the term's IDs, not the tern name. Some say "Get the id's using a custom term search" but doesn't explain how. I know how to do custom taxonumy based queries for posts but not for terms. the documentation confuses me in terms of what values to pass to query terms :(
Other solutions require that I first find a product of a specific category and then find the product's category image working backwards from there (????)
Then of course there is the default answer people love to give for everything: "Oh you are designing your own theme and want to show category icons? Simple, just download a plugin to do that for you". Now why didn't I think of just including someone else's plugin into my theme? (facepalm)
Other answers just show how to print the list of term names but nothing so far has been able to let me do what should have been been as simple as this:
$categories = array("software", "plugins", "merch");
foreach($categories as $cat) {
$term_id = get_term_id($cat);
$term_image = get_term_featured_image($term_id);
echo '<img src="'.$term_image.'">;
}
First problem with getting the term is that the wordpress function to get the term id only works on the category taxonomy but I need to query WooCommerce's product_cat taxonomy. Secondly there doesn't seem to be an option to fetch the thumbnail/featured image even if you HAVE an id. So now what?
So I went low level and started querying the tables directly using $wpdb and I determine the term I am after has term_id 94. I query the termmeta table for the thumbnail's post ID and I find it is 905. Now I turn to my posts table and find.... there IS no post entry 905! WTF? So I do this for two more categories and find the same thing. Finding the image's id results in nothing being returned from the attempt at extracting the post's attachments since there IS no post matching the image's id...
Why is this so darned hard? WordPress makes everything else so incredibly simple yet this simple sounding task seems to be near impossible to do... so now that you see I have Googled this to death and struggled my backside off already, I am asking this question out of desperation:
How do I take an array of product_cat term names and convert that into an array of url's to display the category's image?
Thanks
The shortest way is to use woocommerce_subcategory_thumbnail() dedicated function:
$product_categories = array("software", "plugins", "merch");
// Loop through the product categories
foreach( $product_categories as $category ) {
// Get the WP_term object
$term = get_term_by( 'slug', sanitize_title( $category ), 'product_cat' );
// Get the term link (if needed)
$term_link = get_term_link( $term, 'product_cat' );
// Display the product category thumbnail
woocommerce_subcategory_thumbnail( $term );
}
The other step by step way, that will display the linked product category image with its name:
$product_categories = array("software", "plugins", "merch");
// Loop through the product categories
foreach( $product_categories as $category ) {
// Get the WP_term object
$term = get_term_by( 'slug', sanitize_title( $category ), 'product_cat' );
// Get the term link (if needed)
$term_link = get_term_link( $term, 'product_cat' );
// Get the thumbnail Id
$thumbnail_id = (int) get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
if( $thumbnail_id > 0 ) {
// Get the attchement image Url
$term_img = wp_get_attachment_url( $thumbnail_id );
// Formatted thumbnail html
$img_html = '<img src="' . $term_img . '">';
} else {
$img_html = '';
}
echo '' . $img_html . $term->name . '<br>';
}
Both works…
To get all product categories WP_Term objects and display them with their thumbnails:
// Get all product categories
$product_category_terms = get_terms( array(
'taxonomy' => "product_cat",
'hide_empty' => 1,
));
foreach($product_category_terms as $term){
// Get the term link (if needed)
$term_link = get_term_link( $term, 'product_cat' );
## -- Output Example -- ##
// The link (start)
echo '<a href="' . $term_link . '" style="display:inline-block; text-align:center; margin-bottom: 14px;">';
// Display the product category thumbnail
woocommerce_subcategory_thumbnail( $term );
// Display the term name
echo $term->name;
// Link close
echo '</a>';
}
I want to make the code to display 'MORE STORIES FROM #CATEGORYNAME' as a title of the box that appears. As the user is viewing different category the name to change.
Ex. User is viewing a post in category 'cars' when the box appears the title would be MORE STORIES FROM 'cars'.
When he switch to category 'IT', the name to be 'MORE STORIES FROM IT'
if(!emptry($td_query_more_article->posts)) {?>
<div class="td-more-articles-box">
<i class=td-icon-close td-close-more-articles-box"></i>
<span class="td-more-articles-box-title"><?php echo __td('MORE STORIES', TD_THEME_NAME) ?></span>
<div class="td-content-more-articles-box">
I hope I was specific enough. Corrent me if I am wrong
Sorry, this needs bit more clarification how you want to achieve this; do you want this on widget or add it statically on the theme? Is there a reason why excisting plugins don't work for you?
If you are in the WordPress loop, you can simply using the following:
$categories = get_the_category();
if ( ! empty( $categories ) ) {
echo esc_html( $categories[0]->name );
}
This will give you the first category if there are more than one.
If you are not in the loop, you will need to pass the post id as a parameter, like this;
// get the post object
global $post;
// pass post id
$categories = get_the_category($post->ID);
if ( ! empty( $categories ) ) {
echo esc_html( $categories[0]->name );
}
You can get category name using this function.
$cat_name = get_category(get_query_var('cat'))->name;
I am looking for a function to convert the woocommerce category id into a category slug for a breadcrumb link.
The following loop pulls the upper most product category ID for product pages. This is necessary because some of my products have 4 or 5 levels of hierarchy.
This is working fine.
$prod_terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($prod_terms as $prod_term) {
// gets product cat id
$product_cat_id = $prod_term->term_id;
// gets an array of all parent category levels
$product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' );
// This cuts the array and extracts the last set in the array
$last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
foreach($last_parent_cat as $last_parent_cat_value){
}
}
At this point echo $last_parent_cat_value; would give you the ID of the highest category.
In order to turn this into a breadcrumb link I need to pull the category name. so...
// This function turns Category Ids produced by the foreach loop above into Names
function woocommerceCategoryName($id){
$term = get_term( $id, 'product_cat' );
return $term->name;
}
Now all I need is the slug to complete the link. so...
//this function gets the category slug from the category id
function get_cat_slug($cat_id) {
$cat_id = (int) $cat_id;
$category = &get_category($cat_id);
return $category->slug;
}
but when I echo
echo '' . woocommerceCategoryName($last_parent_cat_value) . '';
My Name function is working but my slug function is not.
Can anyone shine any light into my error?
when I inspect element on the front end here is my generated html...
Sports
Could I try and use the Name to generate the slug?
Thanks for reading.
okay, I am not sure why the above wasn't working, or why the following worked.
//I copied the function to generate the name, and generated a slug instead...
function woocommerceCategorySlug($id){
$term = get_term( $id, 'product_cat' );
return $term->slug;
}
echo '' . woocommerceCategoryName($last_parent_cat_value) . '';
Thanks again for reading, I hope this can help someone else.
I'm displaying the 3 most recent posts from a parent category ("Where We Serve") on a page. Within that parent category, I have 6 other categories named by regions ("Africa", "Europe", "Asia", etc.). The page displays the region category name, and the post content below it. Here's the catch; of these 3 most recent posts, sometimes there will be 2 from the same region category. When that happens, I need the page to show the region category for ONLY the first post from that category. Hopefully this code explains what I'm trying to do:
<div class="news">
<?php
$args = array( 'numberposts' => '3', 'category' => 9 );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
$category = get_the_category($recent["ID"]);
if(
$category == //any previous post's category on this page
){
//echo the post WITHOUT the category name displayed
echo '<h2>'.$recent["post_title"].'</h2><br>'.$recent["post_content"].'<br>';
}
else{
//echo the post WITH the category name displayed
echo '<h1>'.$category[0]->cat_name.'</h1><br><h2>'.$recent["post_title"].'</h2><br>'.$recent["post_content"].'<br>';
}
}
?>
</div>
I don't know how to test for other posts' categories on that page.
As you loop through the posts, save the categories you have used to an array, then check that array to see if the category already exists.
$used_categories = array(); //optional, but for clarity
foreach( $recent_posts as $recent ){
$category = get_the_category($recent["ID"]);
$category_name = $category[0]->cat_name;
if(!isset($used_categories[$category_name])){
//echo the category name displayed
echo '<h1>'.$category_name.'</h1><br />';
//save to used categories. Value assigned doesn't matter
$used_categories[$category_name]=true;
}
//You are outputting this either way, so take it out of the if
echo '<h2>'.$recent["post_title"].'</h2><br />'.$recent["post_content"].'<br />';
}
EDIT: I'm now using Eric G's method.
I wasn't able to get this to work with PHP. I ended up using this javascript at the bottom of the page:
var regionName = document.getElementsByTagName("h1");
if(regionName[1].innerHTML == regionName[0].innerHTML){
regionName[1].style.display="none";
};
if(regionName[2].innerHTML == regionName[1].innerHTML){
regionName[1].style.display="none";
};
Definitely not as clean or "correct" as I was hoping, but it's working for now...