Incorporate a product category on the woocommerce archive/shop page

Attempting to include product category within the product card on the woocommerce archive page. Currently, it displays "Thumbnail," "Title," "Price," and "Add to cart button."

Using a function that should work if the variable "product" is set to the current displayed product.

My Query: Is there a method to retrieve the queried Product in this variable?

Any assistance would be greatly appreciated.

<?php 
// Hook after product title on archive page and execute function "add_category()"
add_action('woocommerce_shop_loop_item_title','add_category');
    // Define function "add_category()"
    function add_category() {
        // define variable "cardcategory"
        $cardcategory = $product->get_categories();
        // create enclosing div
        echo '<div class="category-carousel">';
        // Retrieve current category and convert from plural to singular
        // display singular within <p> element
        if (strpos($cardcategory, 'Category_A_plural') !== false) {
            echo '<p class="Category_A_class">Category A singular</p>';
        }
        if (strpos($cardcategory, 'Category_B_plural') !== false) {
                echo '<p class="Category_B_class">Category B singular</p>';
        }
        // close enclosing div
        echo '</div>';
    }

Answer №1

<?php 
//Add category after product title on archive page
add_action('woocommerce_after_shop_loop_item_title','add_custom_category');

function add_custom_category() {
    global $product; // Ensure global variable is added.

    // Initialize the variable "customcategory"
    $customcategory = $product->get_categories();
    // Display category and convert from plural to singular
    echo '<div class="category-carousel">';

    if (strpos($customcategory, 'Custom_Category_plural') !== false) {
        echo '<p class="Custom_Category_class">Custom Category singular</p>';
    }
    if (strpos($customcategory, 'Another_Custom_Category_plural') !== false) {
            echo '<p class="Another_Custom_Category_class">Another Custom Category singular</p>';
    }
    echo '</div>';
}

Remember to include the line global $product in your code. The variable $product represents an instance of WC_Product, which is likely set by Woocommerce utilizing WordPress' the_post() function internally.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic text input and selection menu with AJAX (PHP and JavaScript)

As a student who is new to Javascript and PHP, I am trying to create a login page for my website that can verify user input in the database using AJAX. For example, when a user enters their username and password, the system should automatically check if t ...

Checkbox form for updating entries in the SQL database table

My goal is to make changes to a MySQL table using an HTML form. Here's a snippet of the form: <div id="caricoModal" class="modal fade"> <div class="modal-dialog"> <form method="post" ...

I am looking to efficiently store and access a collection of form elements, where each group is represented as an array of form elements

I have created a form that consists of groups of elements stored in a database table. I populate the form with data from the table, allowing for edits to be made. Upon submission of the form, changes are saved back to the table based on the submitted form ...

Creating vertically aligned text in Imagick PHP

Is there a way to display text vertically in an imagick image? For instance, if I have the word "test," but I would like the text to appear like this: t e s t Any suggestions on how to achieve this? Thank you. ...

From Jquery to PHP to MySQL: Creating dynamic forms with variable fields

I am facing an issue with a multi-page form that uses multiple MySQL tables to store entered values. One of the pages contains a form that should allow users to click a + button to add extra lines for additional information. The user can add any number of ...

Is there a more effective method than utilizing AppEntity as an alias E?

Is there a more efficient way to load all entities at once without having to load them one by one? I have over 20 entities for my project, and it's time-consuming to write out all the names and code needed on the page. The file header currently looks ...

The suggestions for auto-complete in jQuery are not showing up as expected

I am looking to implement a feature where suggestions from the database are automatically populated in a text box as I type. Additionally, when I select a suggestion, other related text fields should be filled automatically. Below is the code snippet: Vi ...

Interactive Thumbnail Previews

There seems to be an issue with the thumbnail links on my page. The leftmost and rightmost links work fine, but the middle ones are not functioning properly when clicked. The PHP code used to generate these links is the same for all of them, so it's p ...

Having difficulty integrating JSON data from a PHP page into jQuery

I'm having trouble parsing JSON data sent from a PHP page using jQuery. The result I'm getting is just an opening curly brace: { I'm not sure how to fix it. In my PHP code, I'm creating the JSON data like this: $load_op_cm = $DBM -> ...

Exploring the world of PHP and manipulating tag attributes

Working with PHP and DomDocument, I am facing a situation where I have HTML content saved in a database. This content includes anchor tags with various URLs. My goal is to replace any anchor tag hrefs that are not within an allowed URL list with "#". For ...

Retrieve names from MySQL database that contain both spaces and do not contain spaces using the `mysqli` function

I am looking to display rows where the 'tipster' column matches the option selected by the user in the form input. I attempted using replace (tipster ' '. '') LIKE '$tipster' but did not receive any results... Some ...

Enable the option to deactivate specific dates in the datepicker function

In my Laravel application, I have an online appointment form that includes a "Select Doctor" field and a "datepicker." For example, if doctor "A" is available at the clinic on Saturday, Monday, and Wednesday, while doctor "B" is available on Sunday, Tuesd ...

Unable to view images on Wordpress theme

I am currently facing an issue where some images in my asset folder are not displaying properly when I convert my HTML/CSS/JS template to Wordpress. The main problem is with the image that should show up when you first visit the website. Below is the CSS c ...

Having trouble uploading a file sized 300 MB to Amazon S3. The response received is "Internal Server Error."

I keep encountering an "Internal Server Error" whenever I attempt to upload a large file up to 300 MB. The code snippet I am using is as follows: try { $uploader = UploadBuilder::newInstance() ->setClient($s3Client) ->setSource($fileloc) ->setBuc ...

Get rid of the .php extension in the URL completely

Lately, I've been experimenting a lot with the .php extension. I successfully used mod_rewrite (via .htaccess) to redirect from www.example.com/example.php to www.exmaple.com/example. Everything is running smoothly. However, I noticed that even though ...

Utilizing PayPal as a payment method for an exclusive subscription-based online

Running a membership site involves users registering with their email and password, along with subscribing to a monthly plan. The frontend is built using jquery/ajax while the backend utilizes PHP/Slim. Currently, Stripe has been integrated as a payment me ...

Transferring data between two MySQL servers

Typically, I rely on SQLite DB for caching purposes, but I've noticed that queries in MySQL are more efficient. Therefore, I'm interested in restructuring my cache system using MySQL. Currently, my cache structure with SQLite db looks like this: ...

PHP encountering a bad escaped character while parsing JSON using JSON.parse

I'm encountering an issue with JSON parsing. In my PHP code, I have the following: json_encode(getTeams(),JSON_HEX_APOS); This returns a large amount of data. Sample data: To provide more clarity, let's assume I have this: my_encoded_data ...

In a multidimensional array, locate the key corresponding to the specified value

I am facing an issue with my code that involves an array containing various fruits with product ID and price as keys for different values. While I am able to retrieve the correct price, I am struggling to get the name of the chosen product. For instance, ...

Looping through a multidimensional array in $_POST variables

I have developed a form that sends me multiple values using the post function. The $_POST[groups] contains values 1, 2, 4, and 8 based on 4 different checkboxes. Similarly, $_POST[retailgroup] includes only the values 1, 2, and 4. I want to combine these v ...