提问者:小点点

WordPress上的随机插图


如何从/themes/mythemes/gravatar/获取随机图像?我把所有的图片都放在那个目录里,但什么也没发生。

内容目录是否影响代码?或者我应该将所有图像重命名为格式化名称?

我使用这个代码:

function get_images($folder) {

// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';

$str = ''; $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';

$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
    foreach($exts as $ext) { // for each extension check the extension
        if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
            $str .= $file;
            if ($str) $str .= '|';
            ++$i;
        }
    }
}
closedir($handle); // We're not using it anymore
return $str; }

function get_gravatar_images() {
// Get all gravatar images
$str = get_theme_mod('gravatar_img', FALSE);
if ($str !== FALSE) return $str;

$dir = WP_CONTENT_DIR . '/themes/Megumichanz/gravatar/';
if (is_dir($dir)) {
    $str = get_images($dir); 
} else {
    return '';
}       

set_theme_mod('gravatar_img', $str);
return $str;}
function get_my_avatar($comment, $dim) {
static $gravatar_img = NULL;

$img_uri = get_avatar($comment, $dim);
$uri = substring($img_uri, "src='", "s=");
$headers = wp_get_http_headers($uri . "d=404");

// Check the headers
if (!is_array($headers)) :
    $has_valid_avatar = FALSE;
elseif (isset($headers["content-disposition"]) ) :
    $has_valid_avatar = TRUE;
else :
    $has_valid_avatar = FALSE;
endif;

if ($has_valid_avatar) return $img_uri;

// Not valid avatar - return a default based on IP
$img_num = intval($comment->comment_author_email);
if (!$gravatar_img) {
    $gravatar_img = get_gravatar_images();
    if (!$gravatar_img) return $img_uri;

    $gravatar_img = explode('|', $gravatar_img);
}
$img_count = count($gravatar_img);
$index = abs($img_num % $img_count);

// Construct new image http
$img_uri = "<img src='" . get_bloginfo('template_url') . '/gravatar/' . $gravatar_img[$index] . "' width='" . $dim . "' height='" . $dim . "' />";
return $img_uri;}

共1个答案

匿名用户

此代码可能失败的原因有几个,但最有可能的原因是$folder错误。

Wordpress提供了get_stylsheet_directory()函数,供开发人员用于获取主题目录的文件系统路径。对于初学者,您肯定应该使用它来查找您的gravatar文件夹。