search
HomeBackend DevelopmentPHP TutorialAdvanced: Reusable Custom Meta Box: Advanced Fields

In Part 1 of our custom meta box template tutorial series, we covered how to set up a custom meta box that loops through a series of fields and outputs each field as well as the various types of form fields required html. Now we're ready to start adding some advanced items to the array and switch box.


Broadcast Group

Radio buttons are actually never used on their own, as they are used to force the user to select at least one of two options, not as an on/off switch like a checkbox. The first thing we need to do is add the single option to our $custom_meta_fields array.

array (
	'label' => 'Radio Group',
	'desc'	=> 'A description for the field.',
	'id'	=> $prefix.'radio',
	'type'	=> 'radio',
	'options' => array (
		'one' => array (
			'label' => 'Option One',
			'value'	=> 'one'
		),
		'two' => array (
			'label' => 'Option Two',
			'value'	=> 'two'
		),
		'three' => array (
			'label' => 'Option Three',
			'value'	=> 'three'
		)
	)
)

Be sure to add this to the other array items in the original $custom_meta_fields array we started in Part 1.

This array is almost identical to our select box item. It has a main tag, a description, and a unique ID. Define the type and then add the options array. It is important that the option key is the same as the option value because we will later check the saved array to get the saved value.

// radio
case 'radio':
	foreach ( $field['options'] as $option ) {
		echo '<input type="radio" name="'.$field['id'].'" id="'.$option['value'].'" value="'.$option['value'].'" ',$meta == $option['value'] ? ' checked="checked"' : '',' />
				<label for="'.$option['value'].'">'.$option['label'].'</label><br />';
	}
break;

This code will be added after the last "break;" in our meta box switch.

  • Loop through each option in the field nested "options" array
  • Use inline conditions to determine whether the saved value matches the currently opened value, and if true, output the "checked" attribute
  • Use the value of the option as the unique ID of the tag
  • Add a newline character at the end so that the next option is on a new line
  • End with description field. The preceding "
    " is not needed because we left a
  • when looping through the options

CheckboxGroup

We've covered how to use checkboxes as switches and how to select an option from multiple options, but we want to be able to save multiple values ​​for the same field? This is where checkbox groups come in handy.

array (
	'label'	=> 'Checkbox Group',
	'desc'	=> 'A description for the field.',
	'id'	=> $prefix.'checkbox_group',
	'type'	=> 'checkbox_group',
	'options' => array (
		'one' => array (
			'label' => 'Option One',
			'value'	=> 'one'
		),
		'two' => array (
			'label' => 'Option Two',
			'value'	=> 'two'
		),
		'three' => array (
			'label' => 'Option Three',
			'value'	=> 'three'
		)
	)
)

Again we add it to the $custom_meta_fields array and the settings are almost the same as similar fields with a unique id and defined type.

// checkbox_group
case 'checkbox_group':
	foreach ($field['options'] as $option) {
		echo '<input type="checkbox" value="'.$option['value'].'" name="'.$field['id'].'[]" id="'.$option['value'].'"',$meta && in_array($option['value'], $meta) ? ' checked="checked"' : '',' /> 
				<label for="'.$option['value'].'">'.$option['label'].'</label><br />';
	}
	echo '<span class="description">'.$field['desc'].'</span>';
break;

The biggest difference here is that we save this data as an array.

  • Loop through each option defined in the array
  • Store data in an array by adding square brackets at the end of the name: []
  • In the inline condition that outputs the "checked" attribute, use "in_array()" to check whether the value is within the array
  • As before, add a value to each input, close the loop, and output the description

Category selection

It's great to be able to provide custom taxonomies for a variety of purposes, but sometimes you want to limit users to selecting only one term per post. A simple solution is to remove the default select box that WordPress adds to the Compose Post page and add it as a select box to a custom meta box.

array(
	'label' => 'Category',
	'id'	=> 'category',
	'type'	=> 'tax_select'
)

For this example, I will use the built-in taxonomy "Categories". Add this to your $custom_meta_fields array. Make sure the "id" is the same as the category name.

// tax_select
case 'tax_select':
	echo '<select name="'.$field['id'].'" id="'.$field['id'].'">
			<option value="">Select One</option>'; // Select One
	$terms = get_terms($field['id'], 'get=all');
	$selected = wp_get_object_terms($post->ID, $field['id']);
	foreach ($terms as $term) {
		if (!empty($selected) && !strcmp($term->slug, $selected[0]->slug)) 
			echo '<option value="'.$term->slug.'" selected="selected">'.$term->name.'</option>'; 
		else
			echo '<option value="'.$term->slug.'">'.$term->name.'</option>'; 
	}
	$taxonomy = get_taxonomy($field['id']);
	echo '</select><br /><span class="description"><a href="'.get_bloginfo('home').'/wp-admin/edit-tags.php?taxonomy='.$field['id'].'">Manage '.$taxonomy->label.'</a></span>';
break;

We need more information to make this field fully functional than the other fields we have set up.

  • Open the select box and add a blank value as "Select One"
  • Get all terms of the set classification
  • Get the terms saved for the current category
  • Start looping through each term.
  • To keep things simple and readable, we use full-sized conditional statements that output an option if it matches the saved term and a regular option otherwise.
  • When you close the loop and select box, we want to get some information about the classification and store it in a variable.
  • Use description areas as a simple way to link users to areas where taxonomy terms can be managed. Make sure the plurals are correct (there is no such thing as a category) using the tags from the $taxonomy information we collected.

Delete the default category box

Since we want to override the default box with a custom select box without any conflicts in user experience or saving data, it is necessary to remove the taxonomy's edit box from the screen.

function remove_taxonomy_boxes() {
	remove_meta_box('categorydiv', 'post', 'side');
}
add_action( 'admin_menu' , 'remove_taxonomy_boxes' );

You could use the $custom_meta_fields array here to loop through each "tax_select" field and add it to this delete function, but it's probably much simpler to name them individually. You need to know the ID of the category box's div in order to delete it correctly. Learn more about remove_meta_box() in the WordPress Codex.

Save Terms

The final step for this field is to ensure that the taxonomy is saved as-is and not as a custom field. To do this, we'll go back and modify the save_custom_meta() function we created in Part 1 of this series.

First, skip it in the field loop. Find this line:

foreach ($custom_meta_fields as $field) {

Then add this line:

if($field['type'] == 'tax_select') continue;

Then add the following after the foreach loop:

// save taxonomies
$post = get_post($post_id);
$category = $_POST['category'];
wp_set_object_terms( $post_id, $category, 'category' );

This just takes the value from our category select field and sets it as the category term for the post.


发布选择

另一个不太可能但有用的字段是通过将 ID 保存在自定义字段中来将另一个帖子与某个帖子关联起来。这非常类似于 CMS,我发现它对于诸如链接幻灯片帖子类型以转到网站上的另一个帖子或页面之类的事情非常有用,只需从下拉菜单中选择它即可。您可以稍后在另一个函数中使用该 ID 查询该帖子,以从该帖子中获取您需要的任何信息。

array(
	'label' => 'Post List',
	'desc' => 'A description for the field.',
	'id' 	=>  $prefix.'post_id',
	'type' => 'post_list',
	'post_type' => array('post','page')
)

我们这里有所有常见的嫌疑人,但最后我们添加了一个额外的变量来保存您想要在列表中的帖子类型。您可以在此数组中包含帖子、页面和任何其他自定义帖子类型。

// post_list
case 'post_list':
$items = get_posts( array (
	'post_type'	=> $field['post_type'],
	'posts_per_page' => -1
));
	echo '<select name="'.$field['id'].'" id="'.$field['id'].'">
			<option value="">Select One</option>'; // Select One
		foreach($items as $item) {
			echo '<option value="'.$item->ID.'"',$meta == $item->ID ? ' selected="selected"' : '','>'.$item->post_type.': '.$item->post_title.'</option>';
		} // end foreach
	echo '</select><br /><span class="description">'.$field['desc'].'</span>';
break;

您可以添加很多选项来过滤此查询,但我们使用的是对设置帖子类型的所有帖子的基本抓取。

  • 查询所有帖子
  • 打开选择字段并添加空白值
  • 循环遍历每个帖子,并将 ID 设置为选项的值,并将标有帖子类型的标题设置为可供选择的显示文本
  • 关闭循环和选择字段并添加说明

结论

如果到目前为止您一直在关注本系列的两个部分,那么您的最终盒子应该如下图所示:

Advanced: Reusable Custom Meta Box: Advanced Fields

我们确实正在填写可重复使用的模板,用于创建可重复的自定义元框字段,并添加了这种高级甚至非正统的字段。我们将在下一篇文章中用一些更棘手但有用的字段(例如日期选择器和图像上传器)来结束该系列。

The above is the detailed content of Advanced: Reusable Custom Meta Box: Advanced Fields. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

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.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

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.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.