Trying to write a piece of code to expand a theme that I am using in 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.
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.
Found a solution if anyone wants to know.
Changed the 'option' to be the following and removed the code from global $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;
}),
Related
i have created a elementor control in this I have displayed all posts list but while am display the post title in protected function render() then it shows post ID not a post name, I want to display post name and also want to get permalink of that post in Read More
$options = array();
$posts = get_posts( array(
'post_type' => 'digital_card'
) );
foreach ( $posts as $key => $post ) {
$options[$post->ID] = get_the_title($post->ID);
}
$this->add_control(
'post_name',
[
'label' => __( 'Select Posts', 'plugin-domain' ),
'label_block' => ('bool'),
'type' => \Elementor\Controls_Manager::SELECT,
'multiple' => true,
'options' => $options,
]
);
protected function render() {
$settings = $this->get_settings();
$show_title = $settings['post_name'];
?>
<?php echo $show_title; ?>
Read More
<?php
}
}
So you want to get all IDs and post_titles of all custom post_type 'digital_card'?! You don't need $key and get_the_title() to fetch the values for the options of control type Controls_Manager::SELECT2. You can set 'label_block' => true if you want the selection field in full width at the editor panel.
Part within protected function _register_controls():
$options = [];
$posts = get_posts( [
'post_type' => 'digital_card'
] );
foreach ( $posts as $post ) {
$options[ $post->ID ] = $post->post_title;
}
$this->add_control(
'posts',
[
'label' => __( 'Select Posts', 'your-plugin-domain' ),
'type' => \Elementor\Controls_Manager::SELECT2,
'label_block' => true,
'multiple' => true,
'options' => $options,
]
);
So now the IDs of the selected posts will be saved in the control data posts.
To display the post_titles and a link to the related post, you fetch the values by the ID of the posts, which are stored in $settings['posts'] as an array.
Part within protected function render():
$settings = $this->get_settings();
$posts = $settings[ 'posts' ];
foreach( $posts as $post ) {
echo get_the_title( $post );
?>
Read More
<?php
}
add_filter( 'gform_pre_render_6', 'populate_posts' );
add_filter( 'gform_pre_validation_6', 'populate_posts' );
add_filter( 'gform_pre_submission_6', 'populate_posts' );
add_filter( 'gform_admin_pre_render_6', 'populate_posts' );
function populate_posts( $form ) {
$metavalue = $_POST["input_4"];//store the value of the dropdown.
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-posts' ) === false ) {
continue;
}
$args = array(
'numberposts' => -1,
'post_type' => 'member',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'assets',
'value' => $metavalue,
'compare' => 'LIKE'
))
);
//create array based on selection
$posts = get_posts( $args );
$choices = array();
foreach ( $posts as $post ) {
$choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
}
// update 'Select a Post' to whatever you'd like the instructive option to be
$field->placeholder = 'Select a Post';
$field->choices = $choices;
}
return $form;
}
Hi guys,
The purpose of this code is to select from a dropdown which corresponds to a Custom Field, based on the selection, it will then generate a query which based on the metavalue and then put the posts in an array. I was able to store them in an array but I wish to pass a random value from that array to another hidden field in the same form. Is there a more efficient way of doing this particular code?
Thank you so much
You might take a look at Gravity Forms Populate Anything:
https://gravitywiz.com/documentation/gravity-forms-populate-anything/
It will allow you to populate the posts in a Drop Down:
...and then populate data based on the selected item in other fields on the form.
I have built a WooCommerce website for a client with a "Latest Products" page. Due to the competitive nature of the client's industry, the client wants to be able to select certain products to NOT appear amongst the Latest Products.
For this, I have added a custom "Hide from Latest Products" checkbox to the product editor with this code:
add_action('add_meta_boxes', 'gd_add_product_extra_options_metabox');
function gd_add_product_extra_options_metabox(){
add_meta_box("product_extra_options_meta", "Extra Options", "gd_product_extra_options_metabox", "product", "side", "high");
}
// ADD CUSTOM FIELDS //
function gd_product_extra_options_metabox(){
global $post;
// Nonce field to validate form request came from current site
wp_nonce_field( basename( __FILE__ ), 'product_fields' );
// Get the field data if it's already been entered
$hide_from_latest = get_post_meta( $post->ID, 'hide_from_latest', true );
if($hide_from_latest == '1'){$checked = ' checked';}else{$checked = '';}
// Output the field
echo '<p><input type="checkbox" name="hide_from_latest" value="1"' . $checked . '> Hide from Latest Products</p>';
}
And so on and so forth with the saving code, etc. The checkbox appears to work perfectly.
The problem though, is in writing a custom product query to fetch all of the latest products for which this checkbox is NOT checked.
For testing, I have checked and saved the "Hide" option for only 1 product.
I have my query as follows:
$products = new WP_Query( array (
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '100',
'order_by' => 'date',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'hide_from_latest',
'value' => '1',
'compare' => 'NOT LIKE'
),
)
This gives me a very empty screen with "There is no results."
If, however, I change the meta_query to:
'meta_query' => array(
array(
'key' => 'hide_from_latest',
'value' => '1',
'compare' => 'LIKE'
),
)
Then it fetches and displays the 1 single product that I have checked and saved the option for.
I have tried various other options such as using "=" and "!=" for 'compare', I've tried changing the value of the checkbox to "on" and then having 'value' => 'on' in the meta_query, etc. The results are always the same.
Where have I gone wrong?
EDIT:
Here is my full code:
// ADD CUSTOM OPTIONS TO WOOCOMMERCE PRODUCTS //
add_action('add_meta_boxes', 'gd_add_product_extra_options_metabox');
function gd_add_product_extra_options_metabox(){
add_meta_box("product_extra_options_meta", "Extra Options", "gd_product_extra_options_metabox", "product", "side", "high");
}
// ADD CUSTOM FIELDS //
function gd_product_extra_options_metabox(){
global $post;
// Nonce field to validate form request came from current site
wp_nonce_field( basename( __FILE__ ), 'notice_fields' );
// Get the field data if it's already been entered
$hide_from_latest = get_post_meta( $post->ID, 'hide_from_latest', true );
if($hide_from_latest == '1'){$checked = ' checked';}else{$checked = '';}
// Output the field
echo '<p><input type="checkbox" name="hide_from_latest" value="1"' . $checked . '> Hide from Latest Products</p>';
}
// SAVE METABOX DATA //
function gd_save_product_extra_options_metabox( $post_id, $post ) {
// Return if the user doesn't have edit permissions.
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
// Verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times.
if ( !wp_verify_nonce($_POST['notice_fields'], basename(__FILE__)) ) {
return $post_id;
}
// Now that we're authenticated, time to save the data.
// This sanitizes the data from the field and saves it into an array $product_meta.
$product_meta['hide_from_latest'] = esc_textarea( $_POST['hide_from_latest'] );
// Cycle through the $notice_meta array.
foreach ( $product_meta as $key => $value ) :
// Don't store custom data twice
if ( 'revision' === $post->post_type ) {
return;
}
if ( get_post_meta( $post_id, $key, false ) ) {
// If the custom field already has a value, update it.
update_post_meta( $post_id, $key, $value );
} else {
// If the custom field doesn't have a value, add it.
add_post_meta( $post_id, $key, $value);
}
if ( ! $value ) {
// Delete the meta key if there's no value
delete_post_meta( $post_id, $key );
}
endforeach;
}
add_action( 'save_post', 'gd_save_product_extra_options_metabox', 1, 2 );
if( ! function_exists('latest_products_censored') ) {
// Add Shortcode
function latest_products_censored( $atts ) {
global $woocommerce_loop;
// Attributes
$atts = shortcode_atts(
array(
'columns' => '4',
'limit' => '100'
),
$atts, 'products_test'
);
$woocommerce_loop['columns'] = $atts['columns'];
// The WP_Query
$products = new WP_Query( array (
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => $atts['limit'],
'order_by' => 'date',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'hide_from_latest',
'value' => '1',
'compare' => 'NOT LIKE'
),
)
));
ob_start();
if ( $products->have_posts() ) { ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php
} else {
do_action( "woocommerce_shortcode_products_loop_no_results", $atts );
echo "<p>There is no results.</p>";
}
woocommerce_reset_loop();
wp_reset_postdata();
return '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';
}
add_shortcode( 'latest_products_censored', 'latest_products_censored' );
}
After a bit more digging in the Wordpress Codex, I have found the answer!
The meta_query needs to be:
'meta_query' => array(
array(
'key' => 'hide_from_latest',
'value' => '1',
'compare' => 'NOT EXISTS'
),
)
I have just given that a go and it is now working perfectly! :-)
In my shortcode I want to get posts from my custom_type_post but filtering them with ids, post_type and posts_per_page
e.g. [myshortcode type="my_custom_type_post"] - to show all posts in my_custom_type_post
or [myshortcode type="my_custom_type_post" no_of_posts="3"] - to show only 3 posts
or [myshortcode type="my_custom_type_post" no_of_posts="1" id="112"] - to show that specific post
Here is my code. It works when I only send type and posts_per_page and ids BUT doesn't work when I want to display all posts or with no_of_posts
// extracting values from shortcode
extract( shortcode_atts( array (
'type' => '',
'no_of_posts' => '',
'id' => ''
), $atts ) );
$id_array = array_map('intval',explode(',',$id));
$args = array(
'post_type' => $type,
'posts_per_page' => $no_of_posts,
'post__in' => $id_array
);
and then passing the values to wp_query
$query = new WP_Query( $args );
if( $query->have_posts() ){
/*printing out results*/
}
You must have to use conditional code as below
extract( shortcode_atts( array (
'type' => '',
'no_of_posts' => '',
'id' => ''
), $atts ) );
$args['post_type'] = $type;
if($no_of_posts) {
$args['posts_per_page'] = $no_of_posts;
} else {
$args['posts_per_page'] = '-1';
}
if($id) {
$args['post__in'] = array_map('intval',explode(',',$id));
}
I'd just setup arguments based on condition
Hey everyone,
I have a post type called `index`, and i'm trying to build a form for users to insert posts from the frontend.
i created a page and a template for it with a form and an ajax function which insert the content to the DB using `wp_insert_post`. the function works generally, i can see the new posts added to the wp_post db in phpmyadmin. the problem is that i can't see the new posts in the admin panel. the post are counted (i can see the number goes up everytime i try the form), but not shown.
this is the functions.php ajax code (some $_get vars are to be used for meta data inserting):
add_action('wp_ajax_addtoindex', 'addtoindex');
add_action('wp_ajax_nopriv_addtoindex', 'addtoindex');
function addtoindex(){
$title = $_GET["title"];
$slug = sanitize_title_with_dashes($title,'','save');
$group = $_GET["group"];
$inst = $_GET["inst"];
$location = $_GET["location"];
$address = $_GET["address"];
$content = $_GET["content"];
$website = $_GET["website"];
$year = $_GET["year"];
$educ = $_GET["educ"];
$aud = $_GET["aud"];
$teaching = $_GET["teaching"];
$teachers = $_GET["teachers"];
$contact1 = $_GET["contact1"];
$email1 = $_GET["email1"];
$phone1 = $_GET["phone1"];
$contact2 = $_GET["contact2"];
$email2 = $_GET["email2"];
$phone2 = $_GET["phone2"];
$user = get_user_by("login",$authorid);
$authorid = $user->ID;
// Check if the group exists
$group_term = term_exists( $group, 'group', 0 );
// Create group if it doesn't exist
if ( !$group_term ) {
$group_term = wp_insert_term( $group, 'group', array( 'parent' => 0 ) );
}
// Check if the inst exists
$inst_term = term_exists( $inst, 'inst', 0 );
// Create inst if it doesn't exist
if ( !$inst_term ) {
$inst_term = wp_insert_term( $inst, 'inst', array( 'parent' => 0 ) );
}
// Check if the location exists
$location_term = term_exists( $location, 'location', 0 );
// Create location if it doesn't exist
if ( !$location_term ) {
$location_term = wp_insert_term( $location, 'location', array( 'parent' => 0 ) );
}
$custom_tax = array(
'group' => $group_term,
'inst' => $group_inst,
'location' => $group_location
);
//Post Properties
$new_post = array(
'post_title' => $title,
'post_name' => $slug,
'post_content' => $content,
'post_status' => 'pending',
'post_type' => 'index',
'post_author' => $authorid,
'comment_status' => 'closed',
'ping_status' => 'closed',
'tax_input' => $custom_tax
);
//save the new post
if ( post_type_exists( 'index' ) ) {
$pid = wp_insert_post($new_post, true);
echo 'good';
}
else{
echo "bad";
}
// Reset Post Data
wp_reset_postdata();
exit;
}
and this is the index post type code:
function post_type_index() {
register_post_type( 'index',
array(
'label' => __('Index'),
'labels' => array('name' => 'אינדקס האנתרופוסופיה','singular_name' => __('פריט לאינדקס','ohav'),'edit_item' => __('עריכת פריט אינדקס','ohav'),'add_new' => __('הוספת פריט לאינדקס','ohav'),'add_new_item' => __('הוספת פריט לאינדקס','ohav'),'all_items' => __('לכל פריטי האינדקס','ohav')),
'public' => true,
//'publicly_queryable' => true,
//'query_var' => true,
//'capability_type' => 'post',
'has_archive' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'rewrite' =>array(
'slug' => __('index','ohav'),
'with_front' => true
),
'hierarchical' => true,
'supports' => array(
'title',
'boxplace',
'editor',
'thumbnail'
)
)
);
}
add_action('init', 'post_type_index');
okay i found it!
the problem was i already had a pre_get_posts hook that changes the order of the index archive according to the post meta.
add_action( 'pre_get_posts', 'change_order_for_index' );
function change_order_for_index( $query ) {
if ( is_post_type_archive('index') ) {
$query->set( 'meta_key', '_index_featured' );
$query->set( 'orderby', 'meta_value' );
}
}
i added && !is_admin() to the if and it turned okay.
thank you Arif, your answer helped me find it.
you can add an action hook 'pre_get_posts' to include/exclude your custom post type to/from the admin post list or any for any other listing like archives.
add_filter( 'pre_get_posts', 'include_custom_type_index' );
function include_custom_type_index( $query ) {
$query->set( 'post_type', array(
'post', 'index'
));
return $query;
}