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/imghwm/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!

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.