


Unleash the power of conditional tags to supercharge your blog
Conditional tags are one of the many great structures that WordPress has that can help us make WordPress development easier. In this article, we will learn about some of them and use them in sample functions, such as removing content from an error page or changing the icon of an admin page.
What is a "conditional tag"?
They are basically "yes or no questions": they simply return TRUE or FALSE when you use them. We use them in if
statements - if the statement is TRUE or FALSE, we can process our code based on the answer.
You can view all conditional tags in the WordPress Codex.
Now, let’s get to the fun part! There are ten great functions that use conditional tags in this article.
Function 1. Display a pop-up message on the home page is_front_page()
Greeting your visitors from the home page might make them feel happy, or you might give a warning about scheduled maintenance, or you might show a scary pop-up ad. No matter what you need to do, follow these steps:
First, you need to get the Colorbox jQuery plugin here. Get colorbox.min.js (and the corresponding "images" file from the "colorbox/colorbox" folder and colorbox.css folder) to the "colorbox" folder within the theme folder.
Then you need to create a colorbox.load.js file to load the popup. Also put this file into the "colorbox" folder:
jQuery(document).ready(function($) { var $popup = $("#mypopup"); $.colorbox({href:$popup}); });
Afterwards, place the popup HTML code (CSS ID "mypopup
") into your theme's index.php file and hide it in style.css strong> file (with "#mypopup {display:none;}
").
function front_popup() { if(is_front_page()) { // load colorbox.min.js wp_enqueue_script('colorbox-js', get_template_directory_uri().'/colorbox/colorbox.min.js',array('jquery')); // load colorbox.load.js wp_enqueue_script('colorbox-load-js', get_template_directory_uri().'/colorbox/colorbox.load.js',array('colorbox-js')); // load colorbox.css wp_enqueue_style('colorbox-css', get_template_directory_uri().'/colorbox/colorbox.css'); } } add_action('wp_head','front_popup');
Paste it into your functions.php file and you're good to go!
Note: In order to make the pop-up window disappear, you need to add a link to the pop-up window. that's it:
<a href="javascript:$.colorbox.close();">Close</a>
Feature 2. Use is_page()
to include additional CSS and JS code in a specific page
You may need to load some external JavaScript or CSS files for specific pages - such as your About page or a product's download page. Yes, you can include them in your content as well, but this is not a good practice. This is good practice:
function extra_assets() { if(is_page(123)) { // '123' is the ID of the page we are checking for wp_enqueue_script('my-script', get_template_directory_uri().'/some/path/in/your/theme/folder/script.js'); wp_enqueue_style('my-style', get_template_directory_uri().'/some/path/in/your/theme/folder/style.css'); } } add_action('wp_head','extra_assets');
As with the first example, it is enough to add this to your functions.php file. (Don’t forget to change the “123
” number to your page’s ID!)
Function 3. in_category()
"More in this category" section for special category posts
This is not always necessary, but you may want a "More from this category" section for a certain category (but not others). Let's say you have a "News" category and the other categories don't fit into the section we want to create. Conditional tags in_category()
will help us:
function more_from_category($cat_ID) { if(in_category($cat_ID) { $posts = get_posts('numberposts=5&category='.$cat_ID); $output = '<h3 id="More-from-this-category">More from this category</h3>'; $output.= '<ul>'; foreach($posts as $post) { $output.= '<li><a href="'.get_permalink().'">'.get_the_title.'</a></li>'; } wp_reset_query(); $output.= '</ul>'; echo $output; } }
Build this function as needed and add it to your functions.php file. Then, go to single.php and place the code (<?php more_from_category(123); ?>
) where you want that section to appear. All you need to think about is placing the code inside the loop. That's all!
Feature 4. Use is_preview()
to remind yourself (or your author) that you are still on the preview page
This is not required (after all, we are just learning examples of these conditional tags), but it might be a good idea to remind yourself (or your author) that the page shown is the "preview" page. Add this to your theme's functions.php file:
function preview_warning() { if(is_preview()) { echo '<div id="preview-warning">Remember, you\'re still on the Preview page!<div>'; } } add_action('the_content','preview_warning');
Of course, this isn't enough - you need to edit style.css to give the warning text a shape. Something like this:
#preview-warning { background:#800; line-height:50px; font-size:30px; font-weight:bold; text-align:center; position:fixed; bottom:0; }
for you!
Function 5. Use is_404()
to remove certain elements from the 404 page
This is the simplest of all techniques. I think it doesn't even need an explanation - just wrap those "certain elements" (things you don't want to show on the error page, like ads) with the code below and you're good to go! p>
if(!is_404()) { // Here comes the "certain elements". It's that easy. Seriously. }
Function 6. No longer used has_excerpt()
Display automatically generated excerpts
I justhateauto-generated excerpts. So I removed them - using the actual codes provided in the Codex:
function full_excerpt() { if (!has_excerpt()) { echo ''; } else { echo get_the_excerpt(); } }
Add this to the functions.php file and then all you have to do is change the instance of the_excerpt()
to full_excerpt()
.
函数 7. 使用 is_date()
仅列出基于日期的档案中的帖子标题(而不是完整帖子)
有时,在某些存档页面(例如基于日期的存档)上仅列出标题就足够了。因此,例如条件标签 is_date()
,我们将删除循环中除标题之外的内容。
这有点棘手,因为每个主题中的 archive.php 文件都不同。 (如果您的主题中有 date.php 文件,您应该编辑该文件。)在代码中查找 The Loop 并使用以下内容更改 The Loop 内的代码:
if(is_date()) { // If your theme uses h2 headings for post titles, use h2. If it uses h1, use h1. echo '<h2 id="the-title">'.the_title().'</h2>'; } else { // ... // The original code inside The Loop // ... }
功能 8. 使用 is_admin()
如果您喜欢使用 20 个打开的选项卡(全部用于您的博客),那么此技巧可能会非常方便。只需稍微编辑您的网站图标并将其另存为 adminfav.ico - 例如,我的管理面板网站图标只是我原始网站图标的红色版本。
无论如何,您可以这样做:
function admin_favicon() { if(is_admin()) { echo '<link rel="shortcut icon" href="'.get_bloginfo('url').'/adminfav.ico" />'; } } add_action('admin_head','admin_favicon');
函数9. 如果帖子没有,则显示默认缩略图 has_post_thumbnail()
这是一个好的主题必须具备的条件。如果您的主题中有任何显示特色图像缩略图的部分,您应该将 the_post_thumbnail()
函数替换为以下代码:
if(has_post_thumbnail()) { the_post_thumbnail(); } else { echo '<img class="default-thumb lazy" src="/static/imghw/default1.png" data-src="'.get_template_directory_uri().'/images/default-thumb.jpg" .get_template_directory_uri().'/images/default-thumb.jpg" alt="'.get_the_title().'" />'; }
这样,您就可以保持主题外观的一致性。
功能10.使用is_user_logged_in()
为您的登录会员显示一个特殊菜单
如果您在 WordPress 中使用会员系统并拥有会员,您可能需要为您登录的会员创建一个特殊的菜单。方法如下:
function member_menu() { if(is_user_logged_in()) { echo '<div class="member-menu"><h2 id="Member-Menu">Member Menu</h2><ul><li><a href="#">First Menu Item</a></li><li><a href="#">Second Menu Item</a></li><li><a href="#">Third Menu Item</a></li></ul></div>'; } }
这是一个标准的“标题和列表”代码,您应该使用该代码使其像您的侧边栏 div
s 然后放置代码 <?php member_menu(); ?>
在主题的 sidebar.php 文件中。
此外,这只是一个示例,但理想情况下您可以在此处使用 WordPress 自定义菜单和 wp_nav_menu()
。一项标准和一项会员,然后您可以继续从 WordPress 管理仪表板管理它们。您可以在此处阅读有关 wp_nav_menu()
函数的更多信息。
还有其他想法吗?
这是我最喜欢的 10 个使用条件标签的想法。你的呢?如果您有任何要分享的内容,请在下面发表评论,以便我们可以扩展这篇文章并提供更多想法!
The above is the detailed content of Unleash the power of conditional tags to supercharge your blog. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics











There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.
