How to display tags with images. WordPress code example open

How to display tags with images. WordPress code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 5.6 +

The standard WordPress installation does not provide images for taxonomies (tags), but in many cases images attached to tags, categories are very necessary. In this simple guide, we’ll show you how to add images to your tags and then display them on your page.

Class code:

 namespace Typecore; use WP_Term; interface WP_Term_Image_Interface { public static function init( $args = [] ); public static function get_image_id( $term ); } class WP_Term_Image implements WP_Term_Image_Interface { private $args; private static $default_args = [ 'taxonomies' => [], 'noimage_src' => "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100' viewBox='0 0 1000 1000'%3E%3Cpath fill='%23bbb' d='M430 660 l0 -90 -90 0 -90 0 0 -70 0 -70 90 0 90 0 0 -85 0 -85 70 0 70 0 0 85 0 85 90 0 90 0 0 70 0 70 -90 0 -90 0 0 90 0 90 -70 0 -70 0 0 -90z'%3E%3C/path%3E%3C/svg%3E", ]; private static $meta_key = '_thumbnail_id'; private static $attach_meta_key = 'image_of_term'; private function __construct(){} public static function init( $args = [] ){ static $inst; $args = array_filter( (array) $args ); $args = array_intersect_key( $args, self::$default_args ); $inst_key = md5( serialize( $args ) ); if( empty( $inst[ $inst_key ] ) ){ $inst[ $inst_key ] = new self(); $inst[ $inst_key ]->set_args( $args ); $inst[ $inst_key ]->register_hooks(); } return $inst[ $inst_key ]; } private function set_args( array $args = [] ){ $this->args = $args + self::$default_args; if( ! $this->args['taxonomies'] ){ $this->args['taxonomies'] = get_taxonomies( [ 'public' => true ], 'names' ); } } private function register_hooks(){ foreach( $this->args['taxonomies'] as $taxname ){ add_action( "{$taxname}_add_form_fields", [ $this, '_add_term__image_fields' ], 10 ); add_action( "{$taxname}_edit_form_fields", [ $this, '_update_term__image_fields' ], 10, 2 ); add_action( "created_{$taxname}", [ $this, '_create_term__handler' ], 10, 2 ); add_action( "edited_{$taxname}", [ $this, '_updated_term__handler' ], 10 ); // table columns add_filter( "manage_edit-{$taxname}_columns", [ WP_Term_Image_Table_Columns::class, '_add_image_column' ] ); add_filter( "manage_{$taxname}_custom_column", [ WP_Term_Image_Table_Columns::class, '_fill_image_column' ], 10, 3 ); } } public static function get_image_id( $term ){ return (int) get_term_meta( is_object( $term ) ? $term->term_id : $term, self::$meta_key, true ); } public function _add_term__image_fields( $taxonomy ){ wp_enqueue_media(); add_action( 'admin_print_footer_scripts', [ $this, '_add_script' ], 99 ); $this->_css(); ?> <div class="form-field term-group term_image_wrapper_js"> <label><?php _e( 'Image', 'default' ) ?></label> <div class="term__image__wrapper"> <button type="button" class="termeta_img_button termeta_img_button_js"> <img width="100" height="100" alt="" src="<?= $this->args['noimage_src'] ?>"> </button> <button type="button" class="button button-secondary termeta_img_remove_js"><?php _e( 'Remove', 'default' ) ?></button> </div> <input type="hidden" id="term_imgid" name="term_imgid" value=""> </div> <?php } public function _update_term__image_fields( $term, $taxonomy ){ wp_enqueue_media(); add_action( 'admin_print_footer_scripts', [ $this, '_add_script' ], 99 ); $image_id = self::get_image_id( $term ); $image_url = $image_id ? wp_get_attachment_image_url( $image_id, 'thumbnail' ) : $this->args['noimage_src']; $this->_css(); ?> <tr class="form-field term-group-wrap term_image_wrapper_js"> <th scope="row"><?php _e( 'Image', 'default' ) ?></th> <td> <div class="term__image__wrapper"> <button type="button" class="termeta_img_button termeta_img_button_js"><img src="<?= $image_url ?>" alt=""></button> <button type="button" class="button button-secondary termeta_img_remove_js"><?php _e( 'Remove', 'default' ) ?></button> </div> <input type="hidden" id="term_imgid" name="term_imgid" value="<?= $image_id ?>"> </td> </tr> <?php } private function _css(){ ?> <style> .termeta_img_button{ display:inline-block; margin-right:1em; border:0; padding:0; cursor:pointer; /* reset */ } .termeta_img_button img{ display:block; float:left; margin:0; padding:0; width:100px; height:100px; background:rgba(0, 0, 0, .07); } .termeta_img_button:hover img{ opacity:.8; } .termeta_img_button:after{ content:''; display:table; clear:both; } </style> <?php } public function _add_script(){ // выходим если не на нужной странице таксономии //$cs = get_current_screen(); //if( ! in_array($cs->base, array('edit-tags','term')) || ! in_array($cs->taxonomy, (array) $this->for_taxes) ) // return; $title = __( 'Featured Image', 'default' ); $button_txt = __( 'Set featured image', 'default' ); ?> <script> document.addEventListener( 'DOMContentLoaded', function(){ const imgwrap = document.querySelector( '.term_image_wrapper_js' ) if( ! imgwrap ){ return; } const addButton = imgwrap.querySelector( '.termeta_img_button_js' ) const delButton = imgwrap.querySelector( '.termeta_img_remove_js' ) const imgInput = imgwrap.querySelector( '#term_imgid' ) let frame // add / edit addButton.addEventListener( 'click', function( ev ){ ev.preventDefault(); if( frame ){ frame.open(); return; } // задаем media frame frame = wp.media.frames.questImgAdd = wp.media( { states: [ new wp.media.controller.Library( { title : '<?= $title ?>', library : wp.media.query( { type: 'image' } ), multiple: false //date: false } ) ], button: { text: '<?= $button_txt ?>' // Set the text of the button. } } ); // select frame.on( 'select', function(){ let selected = frame.state().get( 'selection' ).first().toJSON(); if( selected ){ imgInput.value = selected.id; let src = selected.sizes.thumbnail ? selected.sizes.thumbnail.url : selected.url imgwrap.querySelector( 'img' ).setAttribute( 'src', src ); } } ); // open media-popup frame.on( 'open', function(){ if( imgInput.value ) frame.state().get( 'selection' ).add( wp.media.attachment( imgInput.value ) ); } ); frame.open(); } ); // remove delButton.addEventListener( 'click', function(){ imgInput.value = ''; imgwrap.querySelector( 'img' ).setAttribute( 'src', '<?= str_replace( "'", "\'", $this->args['noimage_src'] ) ?>' ); } ); } ); </script> <?php } // Save the form field public function _create_term__handler( $term_id, $tt_id ){ $attach_id = isset( $_POST['term_imgid'] ) ? (int) $_POST['term_imgid'] : 0; if( ! $attach_id ){ return; } update_term_meta( $term_id, self::$meta_key, $attach_id ); self::up_attach_term_id( $attach_id, 'add', $term_id ); } // Update the form field value public function _updated_term__handler( $term_id ){ if( ! isset( $_POST['term_imgid'] ) ){ return; } $old_attach_id = self::get_image_id( $term_id ); $attach_id = (int) $_POST['term_imgid']; // update metas if( $attach_id ){ update_term_meta( $term_id, self::$meta_key, $attach_id ); self::up_attach_term_id( $attach_id, 'add', $term_id ); } else{ delete_term_meta( $term_id, self::$meta_key ); } // delete attachment $old_attach = get_post( $old_attach_id ); if( $old_attach && (int) $old_attach_id !== (int) $attach_id ){ $old_attach_term_ids = self::up_attach_term_id( $old_attach_id, 'remove', $term_id ); // Вложение не прикреплено к посту или оно прикреплено к другому термину if( ! $old_attach_term_ids && ! $old_attach->post_parent ){ wp_delete_attachment( $old_attach_id ); } } } /** * Updates post-meta field of specified attachment (post) - adds or removes term id from the field. * * @param int $attach_id * @param string $action add|remove. * @param int $term_id Term id to add/remove to attachment. * * @return array term ids updated fo attachment. */ private static function up_attach_term_id( $attach_id, $action, $term_id ){ $term_ids = wp_parse_list( get_post_meta( $attach_id, self::$attach_meta_key, true ) ); // add if( 'add' === $action ){ $term_ids[] = $term_id; } // remove else { $term_ids = array_diff( $term_ids, [ $term_id ] ); } // join - save as: ,12,34,54, $term_ids = array_unique( (array) $term_ids ); $term_ids = array_map( 'sanitize_text_field', $term_ids ); $joined_term_ids = $term_ids ? ','. implode( ',', $term_ids ) .',' : ''; update_post_meta( $attach_id, self::$attach_meta_key, $joined_term_ids ); return $term_ids; } } class WP_Term_Image_Table_Columns { /** * Adds an image column to the term table. Method for WP hook. * * @param array $columns * * @return array|string[] */ public static function _add_image_column( $columns ){ // fix column width add_action( 'admin_notices', function(){ echo '<style>.column-image{ width:50px; text-align:center; }</style>'; } ); // column has no name return array_slice( $columns, 0, 1 ) + [ 'image' => '' ] + $columns; } public static function _fill_image_column( $string, $column_name, $term_id ){ if( 'image' === $column_name ){ $image_id = WP_Term_Image::get_image_id( $term_id ); $string = $image_id ? sprintf( '<img src="%s" width="50" height="50" alt="" style="border-radius:4px;" />', wp_get_attachment_image_url( $image_id, 'thumbnail' ) ) : ''; } return $string; } } ?> 

Add image

First, we need to connect a class that will add images to our taxonomies. A ready, fast and reliable class from Kama will help us in this.

  1. To start, create a new file in your theme directory and name it for example – class-images-with-thumbnails.php
  2. In the next step, you should plug this class into your functions.php file. This can be done in the following way –
    require get_template_directory() . '/class-images-with-thumbnails.php';

    Require class in yours functions.php file

  3. After connecting, in the same functions.php file, initialize our class by adding the following code:

     add_action( 'admin_init', 'kama_wp_term_image' ); function kama_wp_term_image() { \Typecore\WP_Term_Image::init( [ 'taxonomies' => [ 'category', 'post_tag' ], ] ); } <em>! in the taxonomies parameters, choose for which taxonomies we will connect images category - for <strong>categories</strong>, <strong>post_tag</strong> - for tags, you can also add other taxonomies for which you want to add images here</em> 
  4. Now in the selected taxonomy at the bottom you will see a form for uploading images.
    Form add image

Displaying image

After we have added our images, we need to add them to the frontend of the site, in this example we will display them on a separate page. Let’s start

  1. In the root directory of our theme, next to the file functions.php, we will create a new file and name it, for example tag-list.php
  2. Add the following code to this file:

     <?php /* Template Name: tag-list */ ?> <!-- This line includes the header.php file --> <?php get_header(); ?> <!-- This line sets the current page number to the value of the "page" GET parameter, or 1 if it is not set --> <?php $current_page = isset( $_GET['page'] ) ? $_GET['page'] : 1; ?> <!-- This div contains the main content of the page --> <div class="content"> <!-- This div contains the page title --> <div class="page-title pad group"> <h1> <!-- This line outputs the translated string "List of tags" --> <?php _e( 'List of tags' ); ?> </h1> </div> <!-- This div contains the main content of the page --> <div class="pad group"> <!-- This block of code sets up the query to retrieve tags from the database --> <?php $per_page = 15; $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; $offset = ( $paged - 1 ) * $per_page; $args = array( 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => false, 'number' => $per_page, 'offset' => $offset, 'exclude' => array( '91', '93' ), ); $tags = get_tags( $args ); // This block of code outputs the list of tags if ( $tags ) : $tag = $wp_query->get_queried_object(); ?> <ul class="tags-list"> <?php foreach ( $tags as $tag ) : ?> <li class="tags-list-item"> <!-- This line outputs a link to the tag archive page --> <a href="<?php echo get_tag_link( $tag->term_id ); ?>" class="tags-list-item-link"> <?php $name = get_template_directory_uri(); $thumbnail_id = get_term_meta( $tag->term_id, '_thumbnail_id', true ); $term = get_term( $tag->term_id ); // This block of code outputs the tag thumbnail image if it exists, or a default image if it doesn't if ( $thumbnail_id ) { $thumb_url = wp_get_attachment_image_src( $thumbnail_id, 'thumbnail' ); echo '<img src="' . $thumb_url[0] . '" class="tags-list-item-img" width="120" height="120" alt="' . $tag->name . '" />'; } else { echo '<img src="' . $name . '/img/default_user.jpg' . '" class="tags-list-item-img" alt="' . $tag->name . '" width="120" height="120">'; } // This line outputs the tag name echo $tag->name; ?> </a> <!-- This block of code outputs the number of posts that have this tag --> <small class="tag_count"> <?php echo '<span>' . _e( 'Пісень', 'typecore' ) . ':</span> ' . $term->count; ?> </small> <?php ?> </li> <?php endforeach; ?> </ul> <!-- This block of code outputs the pagination links --> <?php $total_tags = wp_count_terms( 'post_tag', array( 'hide_empty' => false ) ); $total_pages = ceil( $total_tags / $per_page ); if ( $total_pages > 1 ) { echo '<div class="pagination">'; echo paginate_links( array( 'base' => get_pagenum_link( 1 ) . '%_%', 'format' => '/page/%#%', 'current' => $paged, 'total' => $total_pages, 'prev_text' => __( '« Previous' ), 'next_text' => __( 'Next »' ), 'type' => 'plain', 'end_size' => 2, 'mid_size' => 2, ) ); echo '</div>'; } ?> <!-- This block of code outputs a message if no tags are found --> <?php else : ?> <p> <?php _e( 'Not found', ); ?> </p> <?php endif; ?> <!-- This block of code outputs the category description if it exists --> <?php if ( ( category_description() != '' ) && ! is_paged() ) : ?> <div class="notebox"> <?php echo category_description(); ?> </div> <?php endif; ?> </div><!--/.pad--> </div><!--/.content--> <!-- This line includes the sidebar.php file --> <?php get_sidebar(); ?> <!-- This line includes the footer.php file --> <?php get_footer(); ?> 

    ! In this code, we created a new template called “tag-list” using – Template Name: tag-list. We will need this in the next step

  3. Now let’s create a simple page in the WordPress admin and apply this template to it:
    Add new page

That’s all. Now our tag page is available at the page address we created. Enjoy!

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation