Add featured image to wp_nav_menu items - wordpress

This is a self Q&A.
How do you modify the text/html that appears in the output of a wp_nav_menu? For example, I wanted to add the featured image for pages and categories.
You see examples of doing this with a custom walker, but the code is very complex to do for small changes. Surely there is a way to do it with a filter?

This is the code I came up with thanks to some help from a Wordpress StackOverflow answer that I can't find anymore (please comment with a link if you find it).
First you need to add the filter to the specific menu (you could add it to all menus if you want - just use the add_filter line by itself).
// Add filter to specific menus
add_filter('wp_nav_menu_args', 'add_filter_to_menus');
function add_filter_to_menus($args) {
// You can test agasint things like $args['menu'], $args['menu_id'] or $args['theme_location']
if( $args['theme_location'] == 'header_menu') {
add_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
}
return $args;
}
Then you need to build out the code to get the post or category ID from the $item object passed to the filter. It's not as easy as you'd expect, as $item doesn't contain the underlying post/category ID, just the menu item ID. So I use the URL's to do a reverse lookup of the IDs.
This won't work for tags used in a menu, or custom taxonomys. I only needed it for categories, so this is all I built.
// Filter menu
function filter_menu_items($item) {
if( $item->type == 'taxonomy') {
// For category menu items
$cat_base = get_option('category_base');
if( empty($cat_base) ) {
$cat_base = 'category';
}
// Get the path to the category (excluding the home and category base parts of the URL)
$cat_path = str_replace(home_url().'/'.$cat_base, '', $item->url);
// Get category and image ID
$cat = get_category_by_path($cat_path, true);
$thumb_id = get_term_meta($cat->term_id, '_term_image_id', true); // I'm using the 'Simple Term Meta' plugin to store an attachment ID as the featured image
} else {
// Get post and image ID
$post_id = url_to_postid( $item->url );
$thumb_id = get_post_thumbnail_id( $post_id );
}
if( !empty($thumb_id) ) {
// Make the title just be the featured image.
$item->title = wp_get_attachment_image( $thumb_id, 'poster');
}
return $item;
}
And then you want to remove the filter that you applied at the beginning, so that the next menu processed doesn't use the same HTML as defined above in filter_menu_items().
// Remove filters
add_filter('wp_nav_menu_items','remove_filter_from_menus', 10, 2);
function remove_filter_from_menus( $nav, $args ) {
remove_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
return $nav;
}

Modified Drew Baker answer. It works without plugins, also if there is no category with current slug it checks for woocommerce product category ('product_cat').
functions.php
// Add filter to specific menus
add_filter('wp_nav_menu_args', 'add_filter_to_menus');
function add_filter_to_menus($args) {
// You can test agasint things like $args['menu'], $args['menu_id'] or $args['theme_location']
if( $args['theme_location'] == 'menu-header') {
add_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
}
return $args;
}
// Filter menu
function filter_menu_items($item) {
if( $item->type == 'taxonomy') {
// Get category and image ID
$slug = pathinfo( $item->url, PATHINFO_BASENAME );
$cat = get_term_by( 'slug', $slug, 'category' );
// If there is no standard category try getting product category
if( !$cat ) {
$cat = get_term_by( 'slug', $slug, 'product_cat' );
}
$thumb_id = get_term_meta($cat->term_id, 'thumbnail_id', true);
} else {
// Get post and image ID
$post_id = url_to_postid( $item->url );
$thumb_id = get_post_thumbnail_id( $post_id );
}
if( !empty($thumb_id) ) {
// Make the title just be the featured image.
$item->title = wp_get_attachment_image( $thumb_id, 'poster');
// Display image + title example
// $item->title = wp_get_attachment_image( $thumb_id, 'poster').$item->title;
}
return $item;
}
// Remove filters
add_filter('wp_nav_menu_items','remove_filter_from_menus', 10, 2);
function remove_filter_from_menus( $nav, $args ) {
remove_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
return $nav;
}

Related

Remove a category or categories from Breadcrumbs Woocommerce [duplicate]

Please pardon me if there's a better way to do this as I am not very familiar with this code. I would like to display only the link to the homepage and the current product on the breadcrumb.
Desire result:
Currently:
I found the code for the breadcrumb, is there a way to only display the first and last crumb regardless of the hierarchy?
foreach ( $breadcrumb as $key => $crumb ) {
echo $before;
if ( ! empty( $crumb[1] ) && sizeof( $breadcrumb ) !== $key ) {
echo '' . esc_html( $crumb[0] ) . '';
} else if(!is_product() && !flatsome_option('wc_category_page_title')) {
echo esc_html( $crumb[0] );
}
echo $after;
// Single product or Active title
if(is_product() || flatsome_option('wc_category_page_title')){
$key = $key+1;
if ( sizeof( $breadcrumb ) > $key) {
echo ' <span class="divider">'.$delimiter.'</span> ';
}
} else{
// Category pages
if ( sizeof( $breadcrumb ) !== $key + 1 ) {
echo ' <span class="divider">'.$delimiter.'</span> ';
}
}
}
The reason why I am doing this is that some of the products have multiple categories and by default, it will only show the breadcrumb for the primary category. I would rather make a truncated version as suggested by the owner.
I was also wondering if I can simply dynamically retrieve the product title and link + static homepage link, make it into a shortcode so that I can paste it in the product page.
Hi – the first example in the answer above, also removes the shop from woocommerce breadcrumb. Here is a working example, that only removes the category:
// remove only the category from woocommerce breadcrumbs
add_filter( 'woocommerce_get_breadcrumb', 'custom_breadcrumb', 20, 2 );
function custom_breadcrumb( $crumbs, $breadcrumb ) {
//print the array and look for the key with the category
//echo '<pre>';
//print_r($crumbs);
//echo '</pre>';
//unset($crumbs[2]); in my case it is key 2
// only on the single product page
if ( ! is_product() ) {
return $crumbs;
} else {
unset($crumbs[2]); // this isn't enough, it would leave a trailing delimiter
$newBreadC = array_values($crumbs); //therefore create new array
return $newBreadC; //return the new array
}
}
If you want to remove categories and subcategories from product breadcrumbs on the product page you can use the woocommerce_get_breadcrumb hook.
// change the breadcrumb on the product page
add_filter( 'woocommerce_get_breadcrumb', 'custom_breadcrumb', 20, 2 );
function custom_breadcrumb( $crumbs, $breadcrumb ) {
// only on the single product page
if ( ! is_product() ) {
return $crumbs;
}
// gets the first element of the array "$crumbs"
$new_crumbs[] = reset( $crumbs );
// gets the last element of the array "$crumbs"
$new_crumbs[] = end( $crumbs );
return $new_crumbs;
}
The code has been tested and works. Add it to your active theme's functions.php.
A good alternative is to set the primary product category for each product. You can do this by installing the Yoast SEO plugin.
You can use the _yoast_wpseo_primary_product_cat product meta to set the id of the primary product category.
After setting the primary category id by editing the product in the
backend or importing a .csv file you will only need to change the
permalink and breadcrumbs based on the primary product category.
To update the product permalink:
// update the product permalink based on the primary product category
add_filter( 'wc_product_post_type_link_product_cat', 'change_product_permalink_by_cat', 10, 3 );
function change_product_permalink_by_cat( $term, $terms, $post ) {
// get the primary term as saved by Yoast
$primary_cat_id = get_post_meta( $post->ID, '_yoast_wpseo_primary_product_cat', true );
// if there is a primary and it's not currently chosen as primary
if ( $primary_cat_id && $term->term_id != $primary_cat_id ) {
// find the primary term in the term list
foreach ( $terms as $term_key => $term_object ) {
if ( $term_object->term_id == $primary_cat_id ) {
// return this as the primary term
$term = $terms[ $term_key ];
break;
}
}
}
return $term;
}
To update the product breadcrumbs on the product page:
// change the breadcrumb on the product page
add_filter( 'woocommerce_get_breadcrumb', 'custom_breadcrumb', 20, 2 );
function custom_breadcrumb( $crumbs, $breadcrumb ) {
// only on the single product page
if ( ! is_product() ) {
return $crumbs;
}
global $product;
$new_crumbs = array();
if ( $product->get_meta( '_yoast_wpseo_primary_product_cat', true ) ) {
// gets the first element of the array "$crumbs"
$new_crumbs[] = reset( $crumbs );
// gets the id of the primary product category
$primary_cat_id = $product->get_meta( '_yoast_wpseo_primary_product_cat', true );
// create an array with all parent categories (based on the id of the primary product category)
$parent_categories = get_ancestors( $primary_cat_id, 'product_cat' );
$parent_categories = array_reverse($parent_categories);
$parent_categories[] = $primary_cat_id;
// for each product category it gets the name and the permalink
foreach ( $parent_categories as $cat_id ) {
$term = get_term_by( 'id', $cat_id, 'product_cat' );
$new_crumbs[] = array(
0 => $term->name,
1 => esc_url( get_term_link( $term, 'product_cat' ) )
);
}
// gets the last element of the array "$crumbs"
$new_crumbs[] = end( $crumbs );
} else {
// gets the first element of the array "$crumbs"
$new_crumbs[] = reset( $crumbs );
// gets the last element of the array "$crumbs"
$new_crumbs[] = end( $crumbs );
}
return $new_crumbs;
}
The code has been tested and works. Add it to your active theme's functions.php.

How to add a category image menu to my shop page?

I want to add an additional menu consisting only of the product category images. I'm using woocommerce. I would like it to be centered in the middle of the page and drop down. What kind of short code does this require? I've tried using Mega Menu plugin but it only alters my primary menu.
Thanks!
I don't think there is a direct way for that, You can use this code to get an array of the categories images URLs, You can use the "woocommerce_before_shop_loop" action then, loop over the array and put the images in the HTML form you like.
add_action( 'woocommerce_before_shop_loop', function() {
$categories = get_terms( 'product_cat' );
$categories_thumbnails_urls = [];
foreach ( $categories as $category ) {
$thumbnail_id = get_woocommerce_term_meta( $category->term_id, 'thumbnail_id', true );
$thumbnail_url = wp_get_attachment_url( $thumbnail_id );
if ( empty( $thumbnail_url ) ) {
continue;
}
$categories_thumbnails_urls[] = $thumbnail_url;
}
foreach ( $categories_thumbnails_urls as $cat_thumb_url ) {
// ...
}
});

Woocommerce add img tag on order admin details page

I have a wordpress website where customers make an image with text and icons, once processed thru woocommerce and payed for that image name 12345.png is saved as Customer_product_image
function add_order_item_meta($item_id, $values) {
$key = 'customer_product_image'; // Define your key here
$value = $values['user_img']; // Get your value here
woocommerce_add_order_item_meta($item_id, $key, $value);
}
And i works great, but now i'm banning my head against the wall! When the purchased image is displayed on the Order admin detail page, it shows up as CUSTOMER_PRODUCT_IMAGE: 1234.png how on earth would i go about wrapping that within an image tag so the image is displayed there?
I've searched high and low on google but haven't been able to find anything, its probably that i dont know what do actually search for....
This did the trick for me!
First i added this snippet for removing the custom meta item on order detail render:
add_filter( 'woocommerce_hidden_order_itemmeta', 'hide_order_item_meta_fields' );
function hide_order_item_meta_fields( $fields ) {
$fields[] = 'current_view';
$fields[] = 'custom_image';//Add all meta keys to this array,so that it will not be displayed in order meta box
return $fields;
}
second i added it back with this, and with the desired text and image tag:
add_action( 'woocommerce_after_order_itemmeta', 'order_meta_customized_display',10, 3 );
function order_meta_customized_display( $item_id, $item, $product ){
$all_meta_data=get_metadata( 'order_item', $item_id, "", "");
$useless = array(
"_qty","_tax_class","_variation_id","_product_id","_line_subtotal","_line_total","_line_subtotal_tax","_line_tax","_line_tax_data"
);// Add key values that you want to ignore
$customized_array= array();
foreach($all_meta_data as $data_meta_key => $value) {
if(!in_array($data_meta_key,$useless)){
$newKey = ucwords(str_replace('_'," ",$data_meta_key ));//To remove underscrore and capitalize
$customized_array[$newKey]=ucwords(str_replace('_'," ",$value[0])); // Pushing each value to the new array
}
}
if (!empty($customized_array)) {
foreach($customized_array as $data_meta_key => $value){
echo "<div class='product_container'><span>Produkt Billede: </span><img src='".wp_upload_dir()['baseurl'].'/flapper/'. $value ."' /> </div>";
}
}
}
i found the answer to this question on this page
You can use the filter woocommerce_order_item_display_meta_value to output the image. Place this code in your functions.php file, you'll need to modify the src attribute of the img tag to include the appropriate URL before the filename value. You can also modify the display label with the filter woocommerce_order_item_display_meta_key
add_filter( 'woocommerce_order_item_display_meta_value', 'modify_order_item_display_value' , 10, 3 );
function modify_order_item_display_value( $display_value, $meta, $wc_order_item ) {
$meta_data = $meta->get_data();
if( $meta_data['key'] === 'customer_product_image' ) {
return '<img src="' . $meta_data['value'] . '">';
}
return $display_value;
}
add_filter('woocommerce_order_item_display_meta_key', 'modify_order_item_display_key', 10, 3);
function modify_order_item_display_key( $display_key, $meta, $wc_order_item ) {
$meta_data = $meta->get_data();
if( $meta_data['key'] === 'customer_product_image' ) {
return 'Customer Image';
}
return $display_key;
}

Tag cloud and alginment

Is their anyway using the code for wordpress tag list to show the active current tag that is selected ie if they select tag 3 should show it in an orange color the code I am using is as follows in a widget.
<?php wp_tag_cloud( 'format=list&orderby=count&order=DESC' ); ?>
But i not sure on how to do this with css.Also in my blog page the categorys below each post are sitting werid on every post how can i get it to align below Tovább olvasom for every post thanks
The url to check above is
http://kvalixhu.digitalthinkersni.co.uk/blog/
There is a way to style the current tag, but you need to add some code in your theme's functions.php take a look at this site, helped me when I needed that: http://georgebohnisch.com/extending-the-wordpress-tag-cloud/. Here is the code snipped from that site to protect against link rot:
add_filter ( 'wp_tag_cloud', 'tag_cloud_active_class' );
function tag_cloud_active_class( $taglinks ) {
if ( is_tag() ) {
$term_id = get_query_var('tag_id');
$taxonomy = 'post_tag';
$args ='include=' . $term_id;
$terms = get_terms( $taxonomy, $args );
$active_tag = $terms[0]->slug;
}
$tags = explode('', $taglinks);
$regex = "#(.*tag-link[-])(.*)(' title.*)#e";
foreach( $tags as $tag ) {
if (strpos($tag,$active_tag)) {
$tagn[] = preg_replace($regex, "('$1$2 '.'active-tag'.'$3')", $tag );
} else {
$tagn[] = preg_replace($regex, "('$1$2$3')", $tag );
}
}
$taglinks = implode('', $tagn);
return $taglinks;
}
To answer your category problem, what exactly is sitting weird?

How can I use category IDs in WordPress permalinks?

I want to use something like:
http://example.com/%category_id%/%postname%/
for the permalink structure.
For example, if a post has a category with an ID of 3, then the URL for the post will be
http://example.com/3/post-name/
Does anyone know how this can be done? I don't mind modifying WordPress core.
This code adds the %category_id% rewrite tag, and filters post permalinks to replace them with the actual category ID (lowest if there are multiple categories). You can place this in a plugin or in your theme file.
add_action( 'init', 'so6159452_init' );
function so6159452_init()
{
add_rewrite_tag( '%category_id%', '([0-9]+)' );
}
add_filter( 'post_link', 'so6159452_post_link', 10, 2 );
function so6159452_post_link( $permalink, $post )
{
if ( false !== strpos( $permalink, '%category_id%' ) ) {
$cats = get_the_category( $post->ID );
if ( $cats ) {
usort( $cats, '_usort_terms_by_ID' ); // order by ID
$category_id = $cats[0]->cat_ID;
} else {
// Error: no category assigned to this post
// Just use a dummy variable
$category_id = '0';
}
$permalink = str_replace( '%category_id%', $category_id, $permalink );
}
return $permalink;
}

Resources