得到它做它做的事,但认为代码可以使用一些改进:
(添加在空白板上)
在 /wp-content/themes/blankslate/functions.php
//only using single carousel per page now
$vars=array('carouselHtml'=>'<div style="h'.
'eight:100px"><h1>Working, no Carousel</h1></div>',
'css'=>[],
'js'=>[]
);
function getInits(){
global $vars;
return $vars;
}
function setInits() {
global $post;
global $vars;
//see if the page specified a carousel (if value it's the title)
$carousel = get_post_meta($post->ID, 'carousel', true);
//collect all custom fields named "js" usually to fix screen
//re sizing like hiding images or big sliders
$scriptItems = get_post_meta($post->ID, 'js', false);
if ($scriptItems) {
foreach ($scriptItems as $item) {
$vars["js"][]=$item;
}
}
//load all custom fields of the page named css
//can be used for specific styles for the page
$cssItems = get_post_meta($post->ID, 'css', false);
if ($cssItems) {
foreach ($cssItems as $item) {
$vars["css"][]=$item;
}
}
//page has a custom field value named carousel
//it contains the title of the custom post that
//should contain the html, css and js
if ($carousel) {
//nice and intuitive query, gotta love it
$args = array('post_type' =>
'carousel_bootstrap',
'title' => $carousel,
'posts_per_page' => 100);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
$title=the_title(null,null,false);
if($title===$carousel){
//found the custom carousel post, load html
//and add css js not to the page because css
//goes in the top and js goes in the bottom
$tmp=get_post_meta($post->ID, 'js', true);
if($tmp){$vars["js"][]=$tmp;}
$tmp=get_post_meta($post->ID, 'css', true);
if($tmp){$vars["css"][]=$tmp;}
$vars["carouselHtml"]=$post->post_content;
break;
}
endwhile;
//$post was the page at the start of the function
//now it could be the carousel post, not sure
//if the following is needed but works either
//with or without it
wp_reset_postdata();
}
}
//creating custom post named carousel
add_action('init', 'create_carousel_post_type');
function create_carousel_post_type() {
register_post_type( 'carousel_bootstrap', array(
'labels' => array(
'name' => __('Carousels'),
'singular_name' => __('Carousel')
),
'public' => false,
'has_archive' => true,
'rewrite' => array('slug' => 'carousels'),
'show_ui' => true,
'menu_position' => 5,
'supports' => array('title','editor','author',
'thumbnail','custom-fields','revisions')
));
}
在 /wp-content/themes/blankslate/page.php
setInits();
get_header();
....
<body <?php body_class(); ?> id="top">
<!-- Carousel
based on http://getbootstrap.com/2.3.2/examples/carousel.html
================================================== -->
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<?php
$vars=getInits();
echo $vars["carouselHtml"];
?>
在 /wp-content/themes/blankslate/header.php
$vars=getInits();
//output collected css
foreach ($vars["css"] as $item) {
echo '<link rel="stylesheet" type="text/css" href="'.$item.'" />';
}
页脚具有相同类型的代码,但用于 JavaScript。