我无法在这里创建一个完整的解决方案,因为这有点像是“免费为我工作”的问题。
我可以(从全球范围)告诉你如何做到这一点。
wp admin-->课程CPT-->添加元框“选择教师”。收集教师get_posts()
. 将所选教师另存为元,使用update_post_meta($course_post_id, \'assigned_teachers\', $assigned_teachers)
在metabox保存功能中在课程单页模板中,使用get_post_meta($course_post_id, \'assigned_teachers\', true)
. 如果要获取教师帖子的链接,请使用get_permalink($teacher_post_id)
.我希望这足够让你开始了。
<小时>UPDATE (OP添加代码)
您的第一个功能:
function custom_meta_box_markup($object)
{
wp_nonce_field(basename(__FILE__), "meta-box-nonce");
?>
<div>
<select name="meta-box-dropdown">
<?php
$args=array(\'post_type\'=>\'mama_ashpaz\');
$q=new WP_Query($args);
if($q->have_posts()){
$current=0;
while($q->have_posts()){
$q->the_post();?>
<?php $options[$current]=get_the_title();
$option[$current]=get_the_id();
$current++;
}
}wp_reset_postdata();
foreach($options as $key=>$value){
if($value == get_post_meta($object->ID, "meta-box-dropdown", true))
{
?>
<option selected><?php echo $value; ?></option>
<?php
}
else
{
?>
<option><?php echo $value; ?></option>
<?php
}
}
?>
</select>
</div>
<?php
}
有点乱,而且你没有创造
<option>
正确地
这样做:
function custom_meta_box_markup($product)
$options_html = \'\';
$args = array(
\'posts_per_page\' => -1, // get all posts
\'post_type\' => \'mama_ashpaz\',
);
$teacher_posts = get_posts($args);
$selected_teacher = get_post_meta($product->ID, "selected_teacher", true); // notice the different naming, this is more clear.
if($teacher_posts) {
foreach($teacher_posts as $teacher) {
$selected = \'\';
if($teacher->ID == $selected_teacher) $selected = \'selected="selected"\';
// in your code you are not setting the option value.
// When you save the form and collect it with save_post action hook. Only the \'option value=""\' will be passed to the $_POST.
$options_html .= \'<option value="\'.$teacher->ID.\'" \'.$selected.\'>\'.$teacher->post_title.\'</option>\';
}
}
// start the Output
?>
<select name="product_teachers_select">
<?php echo $options_html; ?>
</select>
<?php
}
// If you\'re keeping the above naming, make sure you update the remaining follow-up functions
现在,教师id已保存。检索教师时,您将拥有他的id。通过他的id,您可以收集所需的任何数据,例如:
$teacher = get_post($teacher_id);
$teacher_description = $teacher->post_content;
$teacher_custom_meta = get_post_meta($teacher->ID, \'the_custom_meta_key\', true);
Tip:创建代码时,请尝试命名
params, meta_keys, functions
以任何人都能理解的方式。即使对你自己来说,这也是非常重要的(想象一下,从现在起两年后看你的代码)。
你好,比约恩