A carousel is not just a list of links, it exists to display the links as items in a way that makes them more attractive. In our previous article we saw how to create a carousel, and how to display the HTML elements we need. Now it’s time to build and style our WordPress carousel plugin.
Our carousel is currently a simple list of links, by the end of this article we will have a properly formatted carousel. We’ll see how to apply the styles we need to have the result I showed you in the sample image in Part 1. Of course there are many properties that you can customize, websites don’t have to be the same around the world!
First we’ll look at how we can properly link a CSS file to a web page within WordPress. Then we’ll style our elements, which will demonstrate some CSS tricks that can be useful in many different situations.
Key Takeaways
- The WordPress carousel plugin is enhanced by linking an external CSS file, which allows for easier and more flexible styling. This includes the wp_enqueue_style() function for the inclusion of the file.
- The size of the carousel is defined in the CSS file, with each item filling the entire block created. The positioning of the links and the size of the container is also established.
- The styling of the item’s name, description, and arrows are customized using CSS properties such as display, padding, color, background-color, text-align, and text-shadow.
- The carousel plugin is completed by adding JavaScript to make the arrows functional, allowing for scrolling when the arrows are clicked. This will be covered in the next part of the tutorial.
Linking an External CSS File
To make the styling of our carousel as flexible and easy as possible, we limited the use of inline styles to only one attribute, the background of each item. For all the other styles we will use an external CSS file (stylesheet). You can chose your own name for the file (such as carousel.css) and place it in your plugin’s folder (or in a subdirectory).
To include the file we’ll use the wp_enqueue_style() function as described in our article about the right way to include a script.
We can’t call this function just anywhere, it must be called before the call of wp_head() (unlike a script, we can’t include a CSS file in the footer!). We can use wp_enqueue_scripts, which is called when WordPress includes the scripts and the styles for the current page (in the front-end), so it’s perfect for this application.
The code below must appear in your plugin’s main file.
<span><span>function enqueue_carousel_style() {</span> </span> wp_enqueue_style(<span>'carousel', plugin_dir_url(__FILE__) . 'carousel.css'); </span>} add_action(<span>'wp_enqueue_scripts', 'enqueue_carousel_style');</span>
The wp_enqueue_style() function accepts (at least) two parameters, the name of the style and the URI to the corresponding file. The plugin_dir_url() function will give us the URL to our plugin’s folder, as my carousel.css file is located in the root of this folder I have no subdirectory to add here, but you must concatenate it if you use one.
Note that we’re not testing anything in our function. WordPress will include our CSS file into every page. This is not a problem if you display your carousel on all pages. However, if you display your carousel only on some pages (e.g. only on the home page), you should test whether the visitor is on the right page before including the CSS file (e.g. with is_home()).
Now it’s time to edit our CSS file.
Let’s Style Our Carousel!
The Size of the Carousel
We begin with the size of the main container, the div identified by #carousel. Here you can set the size you want. As we use images that we won’t resize, a fixed size is a good idea.
<span>#carousel { </span><span> <span><span>width: <span>900px</span></span>; </span></span><span> <span><span>height: <span>350px</span></span>; </span></span><span><span>}</span></span>
Later, we will add a third property to this container, overflow. For the moment we won’t use it, that way we can see how our items are laid out across the page.
Each item will fill the entire block we just created. The following rule applies to the item itself (the a tag with the class name carousel-link) as well as its parents.
<span>#carousel ul, </span><span>#carousel ul li, </span><span>#carousel ul li a.carousel-link { </span><span> <span><span>display: block</span>; </span></span><span> <span><span>width: <span>100%</span></span>; </span></span><span> <span><span>height: <span>100%</span></span>; </span></span><span><span>}</span></span>
Positioning the Links
What Happens When We Go to the Right?
Now we have to think about what we want to do. There are many possibilities when we want to build a carousel. I suggest positioning our items next to each other with a float property into a big container: it must be big enough to contain all our items in one line.
When the user wants to see another image, we move this container to align the next item with the #carousel div. This div will have the property overflow set to hidden, that way we won’t see the other links.
Below is a schema of what we want to make. In green you can see the big container with all our links in one line. To let us see the link on the right, the container goes to the left, and vice versa. The black frame represents the #carousel div: outside of this frame, everything is invisible.

The Size of the Container
First, the container: we won’t create another HTML element, as the ul one is perfect for our purposes. We saw that this container must be big enough to contain all our links in one line. Currently this is not the case, our items and our container both have a width of 900 pixels.
To change that, we will increase the width of the container to 500%. The div identified by #carousel has a width of 900 pixels so a width of 500% will allow us to display five links in a row.
<span><span>function enqueue_carousel_style() {</span> </span> wp_enqueue_style(<span>'carousel', plugin_dir_url(__FILE__) . 'carousel.css'); </span>} add_action(<span>'wp_enqueue_scripts', 'enqueue_carousel_style');</span>
A potential problem may occur to you here: the number of items can be variable, as our script can in fact display only three items for example. It’s not really an issue because we limited the number of items to a maximum of five, so even if there are only three they will all fit and the blank space won’t interfere with the operation of the carousel.
If you chose another limit you must change this width (for example to 1000% if you want to display 10). Problems appear when you don’t want any limit. In this case you will have to set the width in the style attribute of the ul tag, based on our $n variable which contains the number of items to be displayed.
<span>#carousel { </span><span> <span><span>width: <span>900px</span></span>; </span></span><span> <span><span>height: <span>350px</span></span>; </span></span><span><span>}</span></span>
Positioning the Links
Now we need to correct the width of the li tags. Currently they are set to 100% so they will take the whole width of our container which is five times too long.
<span>#carousel ul, </span><span>#carousel ul li, </span><span>#carousel ul li a.carousel-link { </span><span> <span><span>display: block</span>; </span></span><span> <span><span>width: <span>100%</span></span>; </span></span><span> <span><span>height: <span>100%</span></span>; </span></span><span><span>}</span></span>
The li tags now have the right width and are floating. If you test our carousel now you will see the right result, five items next to each other. You can now add the overflow property to #carousel to hide the items which should not be visible.
<span>#carousel ul { </span><span> <span><span>width: <span>500%</span></span>; </span></span><span><span>}</span></span>
The Item’s Name and Description
The name of the items can be styled as you desire. Here I will describe how I created the style you saw in the previous part of this tutorial.
As a reminder, the item’s name is displayed in a strong tag in the a.carousel-link element. The strip can be obtained with a background color, but we want this strip to occupy the entire width. To do that we can set display to block. padding and color properties complete the style.
<span><span><span><ul style="width: <?php echo $n * 100; ?></span>%;"></span></span>
As with the name, you can personalize the item’s description. Here I chose to display it on the right, below the name, using the CSS below.
<span>#carousel ul li { </span><span> <span><span>float: left</span>; </span></span><span> <span><span>width: <span>900px</span></span>; </span></span><span><span>}</span></span>
The block value for the display property allows the em tag to use all of the available width. We then align the text on the right, with some padding so the text isn’t hard up against the edge. I chose here a dark grey for the text color. To be sure that the text will always be readable, even on dark images, I added a white text shadow.
Styling the Arrows
The final step is correctly displaying the arrows. You have several choices here, depending on where you want to display these arrows.
I used the properties listed below to achieve the effect on the sample item. We transform the arrows into blocks to be able to modify their sizes, we then fix this size, and we style the arrows. We also use a useful trick to vertically align the text (the arrow), we set the line-height property to the same value we gave to height, the text will then be vertically centered.
<span><span>function enqueue_carousel_style() {</span> </span> wp_enqueue_style(<span>'carousel', plugin_dir_url(__FILE__) . 'carousel.css'); </span>} add_action(<span>'wp_enqueue_scripts', 'enqueue_carousel_style');</span>
To reproduce the rounded corners, we will use border-radius, but not on all the corners, the ones that are on the carousel’s sides shouldn’t be rounded. That’s why we will use the ‘sub-properties’ of border-radius which allow us to select the corners to round.
<span>#carousel { </span><span> <span><span>width: <span>900px</span></span>; </span></span><span> <span><span>height: <span>350px</span></span>; </span></span><span><span>}</span></span>
Finally, I personally like buttons and links to have a hover effect. Here I chose to only modify the color of the arrow.
<span>#carousel ul, </span><span>#carousel ul li, </span><span>#carousel ul li a.carousel-link { </span><span> <span><span>display: block</span>; </span></span><span> <span><span>width: <span>100%</span></span>; </span></span><span> <span><span>height: <span>100%</span></span>; </span></span><span><span>}</span></span>
As CSS3 allows us to easily have a soft transition, why not use them?
<span>#carousel ul { </span><span> <span><span>width: <span>500%</span></span>; </span></span><span><span>}</span></span>
Positioning the Arrows
That’s all for the style of the arrows. Now we need to place them where we want them. We will use absolute positioning, with a little trick: we don’t know the position of the carousel itself so we can’t position the arrows from the screen corners. Instead, we will use the carousel corners and, more precisely, the li tags corners.
Let’s position our arrows with position set to absolute.
<span><span><span><ul style="width: <?php echo $n * 100; ?></span>%;"></span></span>
If you try this, the arrows will be positioned on the screen sides. We must use a less known option of absolute positioning. The arrow element is positioned relative to its closest positioned parent. Here, our arrows do not have any positioned parent so they are positioned relative to the screen.
The problem is the arrows parents are at the right places: we don’t want to move any of them. The trick consists of using relative positioning, without changing anything else. We will apply the relative positioning to the li tags which is the closest parent of our arrows.
<span>#carousel ul li { </span><span> <span><span>float: left</span>; </span></span><span> <span><span>width: <span>900px</span></span>; </span></span><span><span>}</span></span>
Then the arrows are positioned on the side of their closest positioned parent, the li tags, which is what we wanted.
What’s Next?
The HTML elements needed by our carousel are displayed and, now, they are also styled. The problem is that our carousel is totally useless, as it just shows the first item (it was more useful without CSS!).
That’s why we need to add one last thing: JavaScript. In the next (and last) part of this tutorial we will make our arrows function as expected, links will scroll when arrows are clicked. That’s a good thing, right?
The above is the detailed content of Building a WordPress Carousel Plugin: Part 2. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.
