【问题标题】:Shortcode code returns incorrect URL - Wordpress简码代码返回不正确的 URL - Wordpress
【发布时间】:2019-01-30 12:39:51
【问题描述】:

我正在编写一个 WP 短代码来显示输入给出的路径中的随机图像。 [随机图像页面=“”class=“”] 该代码运行良好,但返回正确的 url + 我放置短代码的页面。 例子: 我目前正在本地更新我的网站。 实际网址为:https://localhost/z/ 但是在我完成编码后,它会变成https://localhost/

如果我将简码放在 /prova 页面 (https://localhost/z/prova/) 图像 src 将显示“wp-content/themes/generatepress_child/img/home/2.jpg”,这是正确的,但如果我将鼠标悬停在它上面,它会显示如下完整路径: “https://localhost/z**/prova/**wp-content/themes/generatepress_child/img/home/2.jpg”而不是“https://localhost/z/wp-content/themes/generatepress_child/img/home/2.jpg

我试过改变 $imagesDir $imagesDir = get_site_url() 。 'wp-content/themes/generatepress_child/img/' 。 esc_attr($values['pag']) .'/'; 或 $imagesDir = 'z/wp-content/themes/generatepress_child/img/' 。 esc_attr($values['pag']) .'/'; 甚至: $imagesDir = 'https://localhost/z/wp-content/themes/generatepress_child/img/' 。 esc_attr($values['pag']) .'/';

但所有这些都返回

// 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' );

【问题讨论】:

  • 一个简单的$imagesDir = '/wp-content/...'; 不成功...?
  • @04FS 不,它什么都没有返回
  • 你是什么意思,“它一无所有”?请具体。
  • “图像 src 将显示“wp-content/themes/generatepress_child/img/home/2.jpg”,这是正确的” - “正确”有待商榷这里。这个相对 URL 只能是与特定基本 URI 组合的正确 URL - 与其他 URL 组合则不会。
  • 那么可能是$imagesDir = '/z/wp-content/...';。从您的描述来看,还不清楚图像的实际绝对 URL 是什么。无论如何,根本问题似乎是您不熟悉解析相对 URL 的实际工作原理,因此您应该去某个地方阅读。

标签: php wordpress url random


【解决方案1】:

我已经通过使用

更改返回输出解决了这个问题
'<img src="' . '/z/' . $randomImage . '" class="' . esc_attr($values['class']) . '">';

但我还是不喜欢这个解决方案,有没有更好的解决方法?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多