Tell us what you are trying to do?
Populate a select field for a custom post type dynamically
Is there any documentation that you are following?
Yes: Is the documentation https://toolset.com/documentation/programmer-reference/types-api-filters/#wpt_field_options still up to date? It carries a warning heads-up about future types releases. And it does not work for me currently.
current code:
function g5yearscheck() {
$syear = '2022';
$cyear = date( 'Y', time() );
$year = $syear;
$match = array();
while ($year <= $cyear) {
// Query arguments
$args = array(
'post_type' => 'leistungsreport',
'post_status' => 'private',
'post_title' => $year
);
// Create a new WP_Query instance
$query = new WP_Query( $args );
// Check if the post exists
if ( $query -> have_posts() ) {
// The post exists
$match[] = $year;
error_log( print_r( $match, true ) );
$year++;
continue;
}
$year++;
}
wp_reset_postdata();
return $match;
}
function g5populateyearselect( $current_options, $title_of_field ) {
// each internal annual report post has its year as post title
// so there must be only one editable post per year
// the year selection is to start from 2022 until current year
// form ID: 48004
error_log( 'year select filter start' );
error_log( print_r( $current_options, true ) );
// make sure we have the intended field
if ( $title_of_field != 'Berichtsjahr' ) {
return $current_options;
}
$match = g5yearscheck();
error_log( print_r( $match, true ) );
if ( !empty( $match ) ) {
$new_options[ 0 ] = $current_options[ 0 ];
foreach( $match as $m ) {
$new_options[] = array(
'#value' => $m,
'#title' => intval( $m )
);
}
error_log( print_r( $new_options, true ) );
}
else{
error_log( 'no options' );
}
return $new_options;
}
add_filter( 'wpt_field_options', 'g5populateyearselect', 10, 2 );