mercredi 30 janvier 2019

Shortcode code returns incorrect URL - Wordpress

I'm writing a WP shortcode to disaply random images from a path that's given by input. [random-image pag="" class=""] The code works nicely, but returns the correct url + the page i've put the shortcode. Example: I'm currently renovating my website locally. The actual URL is: https://localhost/z/ But after I've finished coding it will become https://localhost/

If I put the shortcode on /prova page ( https://localhost/z/prova/ ) the image src will show "wp-content/themes/generatepress_child/img/home/2.jpg" which is correct but if I mouse over it it shows the full path like this: "https://localhost/z**/prova/**wp-content/themes/generatepress_child/img/home/2.jpg" instead of "https://localhost/z/wp-content/themes/generatepress_child/img/home/2.jpg"

I've tried changing the $imagesDir in $imagesDir = get_site_url() . 'wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/'; or $imagesDir = 'z/wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/'; or even: $imagesDir = 'https://localhost/z/wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/';

But all of these return with

// Random img 
function random_image(  $atts, $content = null ) {
    $values = shortcode_atts( array(
    'pag'       => 'home',
    'class'     => 'imgrnd',
    ), $atts );

    $imagesDir = 'wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/';

    $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

    $randomImage = $images[array_rand($images)];

    return '<img src="' . $randomImage . '" class="' . esc_attr($values['class']) . '">';

}
add_shortcode( 'random-image', 'random_image' );




Aucun commentaire:

Enregistrer un commentaire