我正在尝试将一个文件夹(文件夹X)中的多个图像(图像A、B和C)随机设置到数据库中,当没有一个设置时,将其作为默认特征图像。
因此,在主页上,我有来自文件夹X的具有不同特征图像的所有帖子。单击“稍后阅读”后,特征图像需要与主页相同。
因此,当发布内容时,如果没有添加任何内容,则需要从文件夹X中获取一幅图像作为特色图像。。
有人知道如何让它工作吗?我自己也是一个PHP新手(不要射击设计师)。。
我正在尝试将一个文件夹(文件夹X)中的多个图像(图像A、B和C)随机设置到数据库中,当没有一个设置时,将其作为默认特征图像。
因此,在主页上,我有来自文件夹X的具有不同特征图像的所有帖子。单击“稍后阅读”后,特征图像需要与主页相同。
因此,当发布内容时,如果没有添加任何内容,则需要从文件夹X中获取一幅图像作为特色图像。。
有人知道如何让它工作吗?我自己也是一个PHP新手(不要射击设计师)。。
感谢@Noob Theory在第一部分帮助了我。
解决方案:将“默认标题”上载到“媒体”并检查其ID。使用array_rand
要将ID随机化,请看,您的操作已完成。
<?
function autoset_featured() {
$media_array = array(
\'1611\',
\'1612\',
\'1613\',
);
$media = $media_array[array_rand($media_array)];
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb) {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
} else {
set_post_thumbnail($post->ID, $media);
}
}
} //end function
add_action(\'the_post\', \'autoset_featured\');
add_action(\'save_post\', \'autoset_featured\');
add_action(\'draft_to_publish\', \'autoset_featured\');
add_action(\'new_to_publish\', \'autoset_featured\');
add_action(\'pending_to_publish\', \'autoset_featured\');
add_action(\'future_to_publish\', \'autoset_featured\');
?>
我不确定随机部分。但是如果没有设置备份特征图像,只需使用
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else { ?>
<img src="<?php bloginfo(\'template_directory\'); ?>/images/default-image.jpg" alt="<?php the_title(); ?>" />
<?php } ?>
或者类似的东西,没有主要的模板编辑function autoset_featured() {
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb) {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
}
}
}
add_action(\'the_post\', \'autoset_featured\');
add_action(\'save_post\', \'autoset_featured\');
add_action(\'draft_to_publish\', \'autoset_featured\');
add_action(\'new_to_publish\', \'autoset_featured\');
add_action(\'pending_to_publish\', \'autoset_featured\');
add_action(\'future_to_publish\', \'autoset_featured\');