Create custom function for hero image

I’m newbies with php development and I want create a custom functions

I would like to create a function that calls an image which has the same name as the product but I fail to call the product name and then place it in the image name. Could you help me please.

my code :

add_action('init', 'custom_hero_image');
function custom_hero_image() {
    $result = get_the_title( 'ID' );
    if ( is_product() ) {
        $html .= '<img class="jarallax-img" src="'. get_template_directory_uri() .'/inc/assets/img/shop/hero/'.$result.'.jpg">';
    } else {
        $html = '<p>No results found.</p>';
    }
    return $html;
}

What I’m doing wrong?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

get_the_title() returns the post (product) title including all HTML, whitespaces and symbols not allowed in URLs, etc. Use post slug instead.

Also, you don’t need to use any actions.

function custom_hero_image( $post_id ) {

    $product = get_post( $post_id ); 
    $slug    = $product->post_name;

    if ( is_product( $post_id ) ) {
        $html = '<img class="jarallax-img" src="'. get_template_directory_uri() .'/inc/assets/img/shop/hero/'.$slug.'.jpg">';
    } else {
        $html = '<p>No results found.</p>';
    }
    return $html;
}

And call the function within a template file:

<div id="hero">
    <?php
        // get the post ID outside the Loop
        $post_id = get_queried_object_id();
        // print the <img>
        echo custom_hero_image( $post_id );
    ?>
</div>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x