如何在Master Slider回调中判断WordPress分类并跳转指定幻灯片
How to Make Master Slider Jump to Specific Slide Based on Post Category
Hey there! Let's get your Master Slider set up to auto-jump to the right slide based on your post's category. Here's a straightforward way to combine WordPress's in_category() function with Master Slider's callback:
Step 1: Define Target Slide Based on Category
First, in your theme's header.php file, add PHP logic to check the post's category and set a target slide number. We'll start with a default value, then override it for specific categories:
<?php // Globalize $post if you're outside the main loop (like in header.php) global $post; // Set default slide to jump to (usually slide 1) $target_slide = 1; // Check post category and update target slide if (in_category('news')) { // Replace 'news' with your category slug/ID/name $target_slide = 2; } elseif (in_category('tutorials')) { $target_slide = 3; } elseif (in_category('reviews')) { $target_slide = 4; } // Add more elseif blocks for additional categories as needed ?>
Step 2: Pass the Target Slide to Master Slider's Callback
Next, integrate this PHP variable into your Master Slider initialization script. We'll convert the PHP value to a JavaScript variable, then use the ready callback to trigger the slide jump:
<script> jQuery(document).ready(function($) { // Pull the target slide number from our PHP variable var targetSlide = <?php echo $target_slide; ?>; // Initialize your Master Slider with your existing config var slider = new MasterSlider(); slider.setup('masterslider', { // Your existing slider settings here width: 1000, height: 600, speed: 15, // ... add any other options you're using }); // Use the 'ready' event to jump to the target slide once the slider loads slider.control.on('ready', function(event) { var api = event.target; // Note: Master Slider's slide numbering starts at 1 (matches your example with gotoSlide(3)) api.gotoSlide(targetSlide); }); }); </script>
Key Notes to Keep in Mind:
in_category()Parameters: You can use a category slug (like'news'), ID (like5), or name (like'Latest News') as the argument.- Slide Numbering: Master Slider uses 1-based indexing for
gotoSlide(), sogotoSlide(1)takes you to the first slide. - Loop Context: If your
header.phpis outside the main post loop, make sure to includeglobal $post;to access the current post's category data.
内容的提问来源于stack exchange,提问作者mitchellvii
相关产品推荐
相关产品推荐

