Woocommerce product option - Wordpress Post titles as a dropdown menu

16 views Asked by At

I am developing a website for a funeral home. On this website (WP, Woo), it should be possible to buy flowers for a deceased person. The deceased persons are WP posts, so their names are WP post titles. So in the product (single) page, there should be a dynamic select field (dropdown) to select the right post title to order flowers for. This dropdown list should ideally be dynamic so that it shows all of the actual post titles. Newly created post titles should be included and deleted post titles, should be not visible anymore.

I used a plugin for this (themehigh - Extra product options) with custom PHP code (below) but the problem is that the post titles are imported. So that newly created post titles don't import automatically and deleted post titles are still shown.

add_filter('thwepo_field_options', 'prepare_field_options', 10 ,2);
 function prepare_field_options($options, $overledene){
    if($overledene == 'overledene') {
        $args = array(
            'post_type'=> 'post',
            'orderby'    => 'id',
            'post_status' => 'publish',
            'order'    => 'DESC',
            'posts_per_page' => -1
        );
        $result = new WP_Query( $args );
        if ( $result-> have_posts() ) :
        while ( $result->have_posts() ) : $result->the_post();
            $title = get_the_title();  
            $options[$title] = array('key'=>$title,'text'=>$title,'price'=>'','price_type'=>'');
        endwhile;
        endif; wp_reset_postdata();
    }
    return $options;
 } 

Is there another way for this?

I also tried another approach where I succesfully made a select field with the actual post titles (via shortcode), but I'm not able to store my selection in the (mini)cart and checkout pages in Woocommerce. (this code below).

// Add a custom shortcode to display post titles in a dropdown menu
function custom_post_titles_dropdown() {
    $args = array(
        'post_type'      => 'post', // Adjust post type if needed
        'posts_per_page' => -1,
        'orderby'        => 'id',
        'order'          => 'DESC',
    );

    $posts = get_posts($args);

    if ($posts) {
        $output = '<select name="post_title" id="post-title-dropdown">';
        $output .= '<option value="">Select Post Title</option>';
        foreach ($posts as $post) {
            $output .= '<option value="' . get_permalink($post->ID) . '">' . get_the_title($post->ID) . '</option>';
        }
        $output .= '</select>';

        return $output;
    }

    return 'No posts found.';
}
add_shortcode('post_titles_dropdown', 'custom_post_titles_dropdown'); 

Is there anyone that can help.

0

There are 0 answers