0

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?

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>
1
  • Thanks a lot, this allowed me to solve my issue but also to understand my errors and thus to be able to code other functions ! 👍🏻
    – GilbertOOl
    Dec 16 '20 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.