Entering multiple selections into database from <select multiple> box - php

I have the bit of code below and I would like uses to select multiple options in the "select multiple" box and for these all to be added into the database. At the moment only 1 of the values that is selected is entered. I am a noob with this sort of thing so an in need of help to progress with the project.
Thanks for any help!
function ProjectTheme_get_categories($taxo, $selected = "", $include_empty_option = "", $ccc = "")
{
$args = "orderby=name&order=ASC&hide_empty=0&parent=0";
$terms = get_terms( $taxo, $args );
$ret = '<select multiple size="20" name="'.$taxo.'_cat" class="'.$ccc.'" id="scrollselect '.$ccc.'">';
if(!empty($include_empty_option)) $ret .= "<option value=''>".$include_empty_option."</o ption>";
if(empty($selected)) $selected = -1;
foreach ( $terms as $term )
{
$id = $term->term_id;
$ret .= '<option '.($selected == $id ? "selected='selected'" : " " ).' value="'.$id.'">'.$term->name.'</option>';
$args = "orderby=name&order=ASC&hide_empty=0&parent=".$id;
$sub_terms = get_terms( $taxo, $args );
foreach ( $sub_terms as $sub_term )
{
$sub_id = $sub_term->term_id;
$ret .= '<option '.($selected == $sub_id ? "selected='selected'" : " " ).' value="'.$sub_id.'"> | '.$sub_term->name.'</option>';
$args2 = "orderby=name&order=ASC&hide_empty=0&parent=".$sub_id;
$sub_terms2 = get_terms( $taxo, $args2 );
foreach ( $sub_terms2 as $sub_term2 )
{
$sub_id2 = $sub_term2->term_id;
$ret .= '<option '.($selected == $sub_id2 ? "selected='selected'" : " " ).' value="'.$sub_id2.'"> |
'.$sub_term2->name.'</option>';
}
}
}
$ret .= '</select>';
return $ret;
}
Here is another section of the code where the user interacts with that form
<li><h2><?php echo __('Category', 'ProjectTheme'); ?>:</h2>
<p><?php echo ProjectTheme_get_categories("project_cat",
!isset($_POST['project_cat_cat']) ? (is_array($cat) ? $cat[0]->term_id : "") : $_POST['project_cat_cat']
, __("Select Category","ProjectTheme"), "do_input"); ?></p>
</li>
Additional code that handles the submit function of the form
do_action('ProjectTheme_post_new_post_post',$pid);
if(isset($_POST['project_submit1']))
{
$project_title = trim($_POST['project_title']);
$project_description = nl2br($_POST['project_description']);
$project_category = $_POST['project_cat_cat'];
$project_location = trim($_POST['project_location_cat']);
$project_tags = trim($_POST['project_tags']);
$price = trim($_POST['price']);
$project_location_addr = trim($_POST['project_location_addr']);
$end = trim($_POST['ending']);
update_post_meta($pid, 'finalised_posted', '0');
//--------------------------------
$projectOK = 1;
if(empty($project_title)) { $projectOK = 0; $MYerror['title'] = __('You cannot leave the project title blank!','ProjectTheme'); }
if(empty($project_category)) { $projectOK = 0; $MYerror['cate'] = __('You cannot leave the project category blank!','ProjectTheme'); }
if(empty($project_description)) { $projectOK = 0; $MYerror['description'] = __('You cannot leave the project description blank!','ProjectTheme'); }
//--------------------------------
$project_category2 = $project_category;
$my_post = array();
$my_post['post_title'] = $project_title;
$my_post['post_status'] = 'draft';
$my_post['ID'] = $pid;
$my_post['post_content'] = $project_description;
$term = get_term( $project_category, 'project_cat' );
$project_category = $term->slug;
$term = get_term( $project_location, 'project_location' );
$project_location = $term->slug;
wp_update_post( $my_post );
wp_set_object_terms($pid, array($project_category),'project_cat');
wp_set_object_terms($pid, array($project_location),'project_location');
wp_set_post_tags( $pid, $project_tags);

Append a [] to Select Tag's name like this <select name="taxo_cat[]" multiple> and in your php code you can access array of values by calling $_POST['taxo_cat']

First of all, to be able to save all selected options, you must send them as an array. For this, the name of the element must be
name="'.$taxo.'_cat[]"
After, on the server side you'll find all selected values in the request variable.
I'm not familiar with Wordpress, but what has changed in your code is
$project_category = $_POST['project_cat_cat'];
$project_location = trim($_POST['project_location_cat']);`
project_category and project_location are now array and not strings, this means you must propably change the way the function get_term() is called, and
wp_set_object_terms($pid, array($project_category),'project_cat');
wp_set_object_terms($pid, array($project_location),'project_location');
has to be changed to
wp_set_object_terms($pid, $project_category,'project_cat');
wp_set_object_terms($pid, $project_location,'project_location');

Related

Send all of a dropdown in Contact Form 7

I need to send a full array of custom field to a mail (dynamicaly populate) with contact Form 7 to work it here before sending :
// define the wpcf7_posted_data callback
function action_wpcf7_posted_data($array)
{
$a = get_field('date')
//WORK HERE
$array['Nom & Prénom'] = $array['name'];
unset($array['name']);
$array['E-mail'] = $array['email'];
unset($array['email']);
$array['Téléphone'] = $array['tel'];
unset($array['tel']);
$array['Profession'] = $array['job'];
unset($array['job']);
$array['Session'] = $array['upcoming-gigs'];
unset($array['upcoming-gigs']);
unset($array['privacy']);
return $array;
}
add_filter('wpcf7_posted_data', 'action_wpcf7_posted_data', 10, 1);
Because it's before sending a mail I can't call anything to compare before sending.
So I want to send all the data in a hidden input next to compare it.
This the two input in contact Form 7 :
[select upcoming-gigs data:gigs id:date] [hidden select upcoming-gigs2 data:gigs2]
My goal here is to send all the data of the hidden select.
I don't find a way to send all input in the mail.
Is it possible ? There is a better way ?
Thx
EDIT :
My question mark2 :
The goal is to send a mail with the date of the session and the id of it.
I use ACF and I have :
And after a dynamic dropdown, it's look like this for the user :
The problem is I don't have the id of the session, only the date.
To know the id I need to compar to the array of all the custom field, I can't import it during wpcf7_posted_data.
I think if I send all the data of the array in a hidden field, I could remake the array and find the id of the session my user choose.
I hope I'm clearer.
(I can't make a request in php during wpcf7_posted_data. Can I make an ajax request ?)
EDIT2 :
This my hidden select with session and text
This is the html of contact form 7 the rest is div for CSS
[select upcoming-date data:date id:date] [hidden select upcoming-date2 data:date2]
EDIT3 :
Okay get it.
The custom fields I use to make the dropdown are in two part id and text. I have the text part I need the id.
If I send every text and id in the mail I can compare to the answer of the user et add to the mail the right id.
Here the generated html : http://www.sharemycode.fr/5ax
EDIT 4 :
That where I write the id and text of the dropdown :
That where I create the select :
add_filter('wpcf7_form_tag_data_option', function ($n, $options, $args) {
$ses = (array)get_field('date_new');
$sesCount = count($ses);
$gigs = [];
$gigs2 = [];
if (in_array('gigs', $options)) {
for ($i = 0; $i < $sesCount; $i++) {
if ($ses[$i]['date_start'] > date('d-m-Y', time())) {
$a = "A réaliser entre le " . $ses[$i]['date_start'] . " et le " . $ses[$i]['date_end'] ." | bla";
array_push($gigs, $a);
}
}
return $gigs;
}
}
It looks like this is supported by Contact Form 7 natively, it's just not very obvious on how to make it happen.
Here's a documentation page explaining the functionality: http://contactform7.com/selectable-recipient-with-pipes/
Basically all you have to do is put the values like so:
Visible Value|actual-form-value
What comes before the pipe "|" character will be shown in the form, and what comes after will be the actual value filled in for the form.
EDIT kanarpp :
I add my code here to separate the answer of HowardE.
This is how I dynamicaly create my select :
add_filter('wpcf7_form_tag_data_option', function ($n, $options, $args) {
$ses = (array)get_field('date');
$sesCount = count($ses);
$date= [];
if (in_array('date', $options)) {
for ($i = 0; $i < $sesCount; $i++) {
if ($ses[$i]['date_start'] > date('d-m-Y', time())) {
$a = "A réaliser entre le " . $ses[$i]['date_start'] . " et le " . $ses[$i]['date_end'] ." | bla";
array_push($date, $a);
}
}
return $date;
}
It's not working, I use Smart Grid-Layout Design for Contact Form 7 to create dynmicaly my select
I would create a custom form tag for the select. The following code will create a custom form tag called [gigs] which would be used like this:
[gigs upcoming-gigs]
I've also included ability to add the * and make it required.
My assumptions are how you're actually getting the ACF fields, which I can't actually do, since I don't have them, and you haven't completely shared how it's stored. You would add this to your functions.php.
add_action('wpcf7_init', function (){
wpcf7_add_form_tag( array('gigs', 'gigs*'), 'dd_cf7_upcoming_gigs' , array('name-attr' => true) );
});
function dd_cf7_upcoming_gigs($tag) {
if ( empty( $tag->name ) ) {
return '';
}
$validation_error = wpcf7_get_validation_error( $tag->name );
$class = wpcf7_form_controls_class( $tag->type );
if ( $validation_error ) {
$class .= ' wpcf7-not-valid';
}
$atts = array();
$atts['class'] = $tag->get_class_option( $class );
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option( 'tabindex', 'signed_int', true );
if ( $tag->is_required() ) {
$atts['aria-required'] = 'true';
}
if ( $validation_error ) {
$atts['aria-invalid'] = 'true';
$atts['aria-describedby'] = wpcf7_get_validation_error_reference(
$tag->name
);
} else {
$atts['aria-invalid'] = 'false';
}
// Make first option unselected and please choose
$html = '<option value="">- - '. __('Please Choose', 'text-domain'). ' - -</option>';
// This part you may have to update with your custom fields
$ses = (array)get_field('date_new');
$sesCount = count($ses);
for ($i = 0; $i < $sesCount; $i++) {
if ($ses[$i]['date_start'] > date('d-m-Y', time())) {
$a = "A réaliser entre le " . $ses[$i]['date_start'] . " et le " . $ses[$i]['date_end'];
// if session ID is in fact $ses[$i]['session']
$html .= sprintf( '<option %1$s>%2$s</option>',
$ses[$i]['session'], $a );
}
}
foreach ($gigs as $key => $value){
$html .= sprintf( '<option %1$s>%2$s</option>',
$key, $value );
}
$atts['name'] = $tag->name;
$atts = wpcf7_format_atts( $atts );
$html = sprintf(
'<span class="wpcf7-form-control-wrap %1$s"><select %2$s>%3$s</select>%4$s</span>',
sanitize_html_class( $tag->name ), $atts, $html, $validation_error
);
return $html;
}
add_filter( 'wpcf7_validate_gigs', 'dd_validate_gigs_filter', 10, 2 );
add_filter( 'wpcf7_validate_gigs*', 'dd_validate_gigs_filter', 10, 2 );
function dd_validate_gigs_filter( $result, $tag ) {
$name = $tag->name;
$has_value = isset( $_POST[$name] ) && '' !== $_POST[$name];
if ( $has_value and $tag->has_option( 'multiple' ) ) {
$vals = array_filter( (array) $_POST[$name], function( $val ) {
return '' !== $val;
} );
$has_value = ! empty( $vals );
}
if ( $tag->is_required() and ! $has_value ) {
$result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
}
return $result;
}

Wordpress custom taxonomy hierarchy insert

I am having some trouble getting this loop to work properly.
I want to insert Country, State, City, Community from google maps as heiarchy in a custom taxonomy of wordpress. All the variables get set but when it runs through the for loop it only populates and inserts the country or 1st array $loop[0].
I am using $pastID[$d] to save the last term_id to use it as the parent in the next term. If this is just bad let me know.
I have to use Globals as I am connecting with an existing plugin also.
$custom_tax_name = "location";
$loop = array();
$loop[0] = $country = $GLOBALS['custom_array']['country'];
$loop[1] = $state = $GLOBALS['custom_array']['state'];
$loop[2] = $city = $GLOBALS['custom_array']['city'];
$loop[3] = $community = $GLOBALS['custom_array']['community'];
$pastID = array();
$terms = array();
for($i = 0; $i<=3; $i++) {
$d = $i - 1;
if (!empty($loop[$i])){
$term_exist = term_exists( $loop[$i], $custom_tax_name );
if (!$term_exist){
if ($i == 0){
$pastID[$d] = wp_insert_term("$loop[$i]", $custom_tax_name);
} else {
if (empty($pastID[$d]['term_id'])){
$term = get_term_by('name', $loop[$i], $custom_tax_name);
$termParent = $term ? $term->parent : false;
if ($termParent == false){
continue;
}
$pastID[$d] = wp_insert_term("$loop[$i]", $custom_tax_name, array("parent" => $termParent));
} else {
$termParent = $pastID[$d]['term_id'];
$pastID[$d] = wp_insert_term("$loop[$i]", $custom_tax_name, array("parent" => $termParent));
}
}
} else {
$pastID[$d] = $term_exist;
}
$terms[] = $loop[$i];
delete_option('{$custom_tax_name}_children');
} // nothing exist
}
Ok So I was able to figure this out after taking a look and feel a little slow here.
the $pastID needed to have $i variable when setting it and $d when referencing it on the next loop. The code below will create a hierarchy taxonomy up to 4+ deep using my variables for country, state, city, and community. It will check if the variable exist and if it does not it will make sure it has a parent to associate it with or not insert it. Anyways thanks.
for($i = 0; $i<=3; $i++) {
$d = $i - 1;
if (!empty($loop[$i])){
$term_exist = term_exists( $loop[$i], $custom_tax_name );
if (!$term_exist){
if ($i == 0){
$pastID[$i] = wp_insert_term($loop[$i], $custom_tax_name);
} else {
if (empty($pastID[$d]['term_id'])){
$term = get_term_by('name', $loop[$i], $custom_tax_name);
$termParent = $term ? $term->parent : false;
if ($termParent == false){
continue;
}
$pastID[$i] = wp_insert_term($loop[$i], $custom_tax_name, array("parent" => $termParent));
} else {
$termParent = $pastID[$d]['term_id'];
$pastID[$i] = wp_insert_term("$loop[$i]", $custom_tax_name, array("parent" => $termParent));
}
}
} else {
$pastID[$d] = $term_exist;
}
$terms[] = $loop[$i];
delete_option('{$custom_tax_name}_children');
} // nothing exist
}

Check equals of tags in array

Good day!
I have archive page, that displays all posts tags in sidebar.
In Archive page i have loop:
global $b;
$i=1;
$b=0;
while( have_posts() ){
the_post();
global $arch_postID;
global $b;
if($i == $num_fetch && $sidebar == 'both-sidebar' ) {
echo '<div class="blog-item' . $item_index . ' gdl-divider ' . $item_class . ' mb30">';
$arch_postID[] = get_the_ID();
echo $i;
}elseif($i == $num_fetch) {
echo '<div class="blog-item' . $item_index . ' gdl-divider ' . $item_class . ' mb20">';
$arch_postID[] = get_the_ID();
echo $i;
}else{
echo '<div class="blog-item' . $item_index . ' gdl-divider ' . $item_class . ' mb50">';
$arch_postID[] = get_the_ID();
echo $i;
}
$b++;
$i++;
In function.php for sidebar i have:
global $arch_postID;
global $b;
global $archive_uri;
if ( !empty($arch_postID) && is_archive() ){
echo '<style>.archive-hide-side{display:none;}</style>';
for($i = 0; $i <= $b-1; $i++){
$array_keys = array_keys($arch_postID);
$terms_array = wp_get_post_terms($arch_postID[$i],'vip'); // Get terms for post_id in array( $arch_postID[0], $arch_postID[1] ... )
$terms_array_next = wp_get_post_terms($arch_postID[$i+1],'vip'); // Get terms for post_id in array( $arch_postID[1], $arch_postID[2] ... )
$terms_array_last = wp_get_post_terms($arch_postID[$b-1],'vip'); // Get terms for $arch_postID[$i = last]
$terms_array_first = wp_get_post_terms($arch_postID[0],'vip'); // Get terms for first post ID
for($a = 0; $a <= count($a)+1; $a++){
$name_array = $terms_array[$a]->name;
$name_array_next = $terms_array_next[$a]->name;
$name_array_last = $terms_array_last[$a]->name;
$name_array_first= $terms_array_first[$a]->name;
if( $name_array == $name_array_next or $name_array_next == $name_array_last or $name_array_last == $name_array_first ){ // check if next term->name is similar to previous of last, or first
$name_array_next = NULL; // assigned NULL to value of term->name
$name_array_last = NULL; // assigned NULL to value of term->name
$name_array_first = NULL; // assigned NULL to value of term->name
echo '<div style="color:black">'. $arch_postID[$i] .' || '. $name_array .'</div>'; // Display term->name values without next or previous term->name
}
}
}
}
This code works like - prntscr.com/7rrozc - displays all tags( on right side ) and post ID(on left side ) divided by "||" from current archive page posts.
End result:
I need to display only one tag, if it similar to another.
I have two posts, their tags: first post( "vip 1", "vip 2", "vip 3", "OTHER" ), second post( "vip 1", "vip 2", "OTHER 2").
In sidebar must be displayed "vip 1", "vip 2","vip 3","OTHER","OTHER 2".
I'm stuck on that question for two days, i have no solution in my mind... If someone knows how to do that, pls help me out. I would be happy for a little hint.
P.S. Thanks for you help and time!
I find solution, works great!
$Path=$_SERVER['REQUEST_URI'];
$Prev_path=$_SERVER['HTTP_REFERER'];
$URI='http://gradrich.tmweb.ru'.$Path;
global $arch_postID;
global $b;
global $archive_uri;
global $brr;
if ( !empty($arch_postID) && is_archive() ){
for($i = 0; $i <= $b-1; $i++){
$terms_array = wp_get_post_terms($arch_postID[$i],'super_vip');
for($a = 0; $a <= 100; $a++){//goes a 100 time from 0, to show all parameters from wp_get_post_terms array
$terms_name[] = $terms_array[$a]->name;// create array of terms->name
$terms_slug[] = $terms_array[$a]->slug;// create array of terms->slug
}
}
$result_name = array_unique($terms_name);// check name array for unique variables
$result_slug = array_unique($terms_slug);// check slug array for unique variables
for($f = 0, $s = 0; $f <= count($terms_name), $s <= count($terms_slug); $f++, $s++){// do loop for all unique variables
if(!empty($result_name[$f]) && !is_category() || !empty($result_slug[$s]) && !is_category()){//check if variables not empty than get proper name and slug from two arrays
echo '<div class="tagCloud-cover" id="cat-hide">' . $result_name[$f] . '<a href="'. $Prev_path .'" >-</a></div>';
} else{
}
}
}

PHP: How to insert a <br/>-tag after the # inside an email address

I'm having problems with some email addresses that are too long. So I'd like to set a break after the # character.
But unfortunately, the # symbol seems to be a special character. That's why it doesn't work with:
str_replace ('#' , '#<br/>' , $email);
Is there any other way to get it done?
I'll make an attempt at hopefully answer this question, seeing that you are most likely not showing us your full code.
If by any chance that you're using another function in conjunction with this, say for example strlen(), then that could account for it, and how you're using it.
You may also be using another function, which is unknown at the time of your posting. Therefore you will need to elaborate on that, should my answer not provide you with a solution.
Far as I'm concerned, your "posted" code checked out, so I can't see how that could be failing.
Using the following and in conjunction with your posted code, proved to be successful.
<?php
// email with 33 characters
$email = "emailwith33characters#example.com";
// if more or equal to 33 characters
if(strlen($email) >= 33){
echo "The email <b>$email</b> contains 33 or more characters. ";
echo "Now putting them into 2 lines...";
echo "<br>";
// echo str_replace('#', '#<br/>', $email);
echo "First line: " . str_replace('#', '#<br/>Second line: ', $email);
}
else{
echo "Email is within character limit.";
}
Using echo strlen($email); will show you the email's string length.
Reference(s):
http://php.net/strlen
http://php.net/str_replace
Thank you for your help. Unfortunately "str_replace" does not work with the "#" character in my code. If I test it with the "." character it sometimes works. Ever time I reload the page in the browser the "str_replace" result changes.
Here's some more of the code. It's from a Wordpress plugin to show contact details of staff members. It loops through all staff posts.
$i = 0;
if( $staff->have_posts() ) {
if ($headline =='yes') {
$output .= '<h1 class="staff-group-mainheader">'.$maingroupname.'</h1>';
}
$output .= '<div class="staff-member-listing '.$group.'">';
while( $staff->have_posts() ) : $staff->the_post();
unset($staff_member_classes);
$terms = get_the_terms( $post->id, 'staff-member-group' ); // get an array of all the terms as objects.
$term_slug = array(); // save the slugs in an array
$term_name = array(); // save the slugs in an array
foreach( $terms as $term ) {
$term_slug[] = $term->slug; // this grabs the hyphenated slug
$term_name[] = $term->name; // this grabs the actual name
$staff_member_classes .= ' '.$term->slug;
}
if ($i == ($staff->found_posts)-1) {
$staff_member_classes .= " last";
}
if ($i % 2) {
$oddorevenpost = 'even';
} else {
$oddorevenpost = 'odd';
}
if (($oddorevenpost == $oddoreven) || ($oddoreven == '')) {
$output .= '<div class="staff-member '.$oddorevenpost.' '.$staff_member_classes.'">';
global $post;
$custom = get_post_custom();
$name = get_the_title();
$name_slug = basename(get_permalink());
$title = $custom["_staff_member_title"][0];
$function = $custom["_staff_member_fb"][0];
$email = antispambot($custom["_staff_member_email"][0]);
if (!empty($custom["_staff_member_phone"][0])) {
$phone = '<li><i class="icons lycon-phone"></i><span class="staff-phone">'.$custom["_staff_member_phone"][0].'</span></li>';
}
if (!empty($custom["_staff_member_mobile"][0])) {
$mobile = '<li><i class="icons icon-mobile-6"></i><span class="staff-mobile">'.$custom["_staff_member_mobile"][0].'</span></li>';
}
if (!empty($custom["_staff_member_fax"][0])) {
$fax = '<li><i class="icons lycon-fax"></i><span class="staff-fax">'.$custom["_staff_member_fax"][0].'</span></li>';
}
$company = $custom["_staff_member_company"][0];
$street = $custom["_staff_member_street"][0];
$city = $custom["_staff_member_city"][0];
$country = $custom["_staff_member_country"][0];
$bio = $custom["_staff_member_bio"][0];
if(has_post_thumbnail()){
$postidthumb = wp_get_attachment_url( get_post_thumbnail_id($post->ID));
$photo_url = wp_get_attachment_medium_url( $postidthumb );
$photo = '<div class="staff-member-container" style="background: url('.$photo_url.') no-repeat right bottom;">';
}else{
$photo_url = '';
$photo = '';
}
if (function_exists('wpautop')){
$bio_format = '<div class="staff-member-bio">'.wpautop($bio).'</div>';
}
$emailbreak = str_replace ('#' , '#<br/>' , $email);
$email_mailto = '<li><i class="icons icon-mail-7"></i><span class="staff-email"><a class="staff-member-email" href="mailto:'.$email.'" title="Email '.$name.'">'.$emailbreak.'</a></span></li>';
$email_nolink = antispambot( $email );
$accepted_single_tags = $default_tags;
$replace_single_values = array($name, $name_slug, $photo_url, $title, $function, $email_nolink, $phone, $mobile, $fax, $company, $street, $city, $country, $bio, $fb_url, $tw_url);
$accepted_formatted_tags = $default_formatted_tags;
if ( $title =='') {
$formattedname = '<h3 class="staff-member-name">'.$name.'</h3>';
} else {
$formattedname = '<h3 class="staff-member-name">'.$title.' '.$name.'</h3>';
}
$replace_formatted_values = array($formattedname, '<h4 class="staff-member-position">'.$title.'</h4>', $photo, $email_mailto, $bio_format );
$loop_markup = str_replace($accepted_single_tags, $replace_single_values, $loop_markup);
$loop_markup = str_replace($accepted_formatted_tags, $replace_formatted_values, $loop_markup);
$output .= $loop_markup;
$loop_markup = $loop_markup_reset;
$output .= '</div> <!-- Close staff-member -->';
}
$i += 1;
endwhile;
$output .= "</div> <!-- Close staff-member-listing -->";
}
}
wp_reset_query();
$output = $style_output.$output;

Run custom shortcode twice in the same page

I need help with a wordpress question.
I created a custom shortcode that retrieves a list of data inside a table with specific paramenter:
add_shortcode("archive", "archive_render");
function archive_render($atts) {
extract(shortcode_atts(array(
"rientro" => "no",
"year" => "",
), $atts));
global $wpdb;
$rientro == "si" ? $rientro = "yes" : "no";
$query = "SELECT event_name FROM wp_em_events WHERE EXTRACT(YEAR FROM event_end_date) = ".$year." AND event_end_date < CURDATE()";
$pasts_event = $wpdb->get_col($query);
function get_pasts_event( $pasts_event ){
foreach ( $pasts_event as $past_event_slug ) {
$output .= "<li><a href='".get_site_url()."/eventi/".$past_event_slug."'>$past_event_slug</a></li>";
}
return $output;
}
$string = '[one_third last="'.$rientro.'" class="" id=""][accordian class="" id=""][toggle title="'.$year.'" open="no"]<ul>'.get_pasts_event($pasts_event).'</ul>[/toggle][/accordian][/one_third]';
echo do_shortcode( $string );
}
I want to retrieve all events that has past date compared with the current date.
If I add the shortcode twice in the page, only the first shortcode works and the page stop to display the rest of the content.
Anybody can help me to solve this problem?
wordpress shortcode should return a string, not echoing it
let me re-arrange your code
function get_pasts_event( $pasts_event ){
foreach ( $pasts_event as $past_event_slug ) {
$output .= "<li><a href='".get_site_url()."/eventi/".$past_event_slug."'>$past_event_slug</a></li>";
}
return $output;
}
add_shortcode("archive", "archive_render");
function archive_render($atts) {
extract(shortcode_atts(array(
"rientro" => "no",
"year" => "",
), $atts));
global $wpdb;
$rientro == "si" ? $rientro = "yes" : "no";
$query = "SELECT event_name FROM wp_em_events WHERE EXTRACT(YEAR FROM event_end_date) = ".$year." AND event_end_date < CURDATE()";
$pasts_event = $wpdb->get_col($query);
$string = '[one_third last="'.$rientro.'" class="" id=""][accordian class="" id=""][toggle title="'.$year.'" open="no"]<ul>'.get_pasts_event($pasts_event).'</ul>[/toggle][/accordian][/one_third]';
return $string;
}

Categories