[英]Get Custom Posts and put into option array - wordpress plugin
Trying to write a piece of code to expand a theme that I am using in Wordpress. 尝试编写一段代码以扩展我在Wordpress中使用的主题。
Basically, I want to get all custom post types and put it into an array for a select - the issue I am having is that I need to add the option values in the array and I cannot put a foreach loop in the array so not sure how to do this. 基本上,我想获取所有自定义帖子类型并将其放入数组中进行选择-我遇到的问题是我需要在数组中添加选项值,而我无法在数组中放置foreach循环,所以不确定这个怎么做。
In the code below you will see the code: 在下面的代码中,您将看到代码:
'options' => array(),
This is where the custom posts need to be in the format: 这是自定义帖子需要采用以下格式的地方:
'PostID' => esc_html__( 'Post Name', 'builder' ),
Here is my code: 这是我的代码:
function get_fields() {
$fields = array(
'get_post_names' => array(
'label' => esc_html__( 'Url Opens', 'builder' ),
'type' => 'select',
'option_category' => 'configuration',
'options' => array(),
'toggle_slug' => 'post_names',
'description' => esc_html__( 'Here you can choose whether or not your link opens in a new window', 'et_builder' ),
),
);
global $wpdb;
$custom_post_type = 'custom_post_name';
$results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A );
if ( ! $results )
return;
foreach( $results as $index => $post ) {
$fields['options'][] = array (
$post['ID'] => esc_html__( $post['post_title'], 'builder' ),
);
}
return $fields;
}
Any help would be much appreciated. 任何帮助将非常感激。
Thanks 谢谢
Hopefully this may work 希望这可能工作
function generate_post_select($select_id, $post_type, $selected = 0) {
$post_type_object = get_post_type_object($post_type);
$label = $post_type_object->label;
$posts = get_posts(array('post_type'=> $post_type, 'post_status'=> 'publish', 'suppress_filters' => false, 'posts_per_page'=>-1));
foreach ($posts as $post) {
echo $post->post_title;
}
}
$select_id
is used as the name and id of the select, $post_type
is the type you want to be made into the select and $selected
is the post id you want selected in the select box. $select_id
用作选择的名称和ID, $post_type
是要在选择中输入的类型, $selected
是要在选择框中$selected
的帖子ID。
Found a solution if anyone wants to know. 找到一个解决方案,如果有人想知道。
Changed the 'option' to be the following and removed the code from global $wpdb; 将“选项”更改为以下内容,并从全局$ wpdb中删除了代码; down. 下。
'options' => array_reduce( get_posts( 'post_type=custom_post&posts_per_page=-1' ), function( $result, $item ) {
$result[$item->ID] = $item->post_title;
return $result;
}),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.