قم بتعيين القيمة إلى الحقل المخصص أثناء الإرسال
-
09-12-2019 - |
سؤال
هل من الممكن تعيين قيمة تلقائية لحقل مخصص أثناء إرسال المنشور في ووردبريس؟
عندما أنشر، أحتاج إلى أن يأخذ هذا الحقل المخصص تلقائيًا الحرف الأول من عنوان المنشور.
مثال:إذا كان عنواني هو "مثال" فإن قيمة الحقل المخصص هي "E".
المحلول
نعم هذا ممكن.إذا كنت تضيف حقلاً مخصصًا بواسطة صندوق التعريف، فيمكنك القيام بذلك على النحو التالي:
// add action to create your custom field
add_action( 'add_meta_boxes', 'create_meta_box' );
// add a callback that will be called when saving the post
add_filter( 'save_post', 'save_meta_box', 10, 2 );
// function that will create a meta box
function create_meta_box() {
add_meta_box('sample_meta_box', __('Sample Box'), 'display_meta_box');
}
// function that will display the actual meta box
function display_meta_box($post, $metabox) {
?>
<input name="sample" type="text" id="sample" value="<?php echo get_post_meta($post->ID, 'sample', true); ?>">
<?php
}
// function that will be called when the post is saved
function save_meta_box($post_id, $post) {
// default value for the field
$value = $_POST['post_title'][0];
// only use the default value if user haven't specified one
if(!empty($_POST['sample'])) {
$value = $_POST['sample'];
}
// update the meta data for the post
update_post_meta($post_id, 'sample', $value);
}
بالطبع سوف تضطر إلى التغيير sample
في هذه الحالة إلى اسم حقل بيانات التعريف الخاص بك.
إذا قمت بالفعل بإنشاء حقل مخصص من خلال واجهة الإدارة، فيمكنك القيام بما يلي:
// add a callback that will be called when saving the post
add_filter( 'save_post', 'save_custom_field', 10, 2 );
// called when updating a post
function save_custom_field($post_id, $post) {
// loop through the meta data
if(isset($_POST['meta'])) {
foreach($_POST['meta'] as $key => $value) {
// check if it's the correct field
if($value['key'] == 'sample') {
// this will always set the custom field to the first letter in the title
update_post_meta($post_id, 'sample', $_POST['post_title'][0]);
break;
}
}
}
}
كما في المثال الأول، سيتعين عليك تغيير sample
إلى اسم الحقل المخصص الخاص بك.
لا تنتمي إلى wordpress.stackexchange