Skip to content

Instantly share code, notes, and snippets.

@tripflex
Created November 1, 2023 21:40
Show Gist options
  • Save tripflex/78e421be1b7274fa1c4d9c75ae6afd1b to your computer and use it in GitHub Desktop.
Save tripflex/78e421be1b7274fa1c4d9c75ae6afd1b to your computer and use it in GitHub Desktop.
Populate Post Names for Dropdown field when using WP Job Manager Search and Filtering
<?php
function smyles_populate_post_titles( $section_data, $section_id, $section ) {
if ( ! isset( $section_data['fields'] ) || ! is_array( $section_data['fields'] ) ) {
return $section_data;
}
foreach ( $section_data['fields'] as $field_id => $field ) {
if ( $field['search_source'] == 'job_title' ) {
// Check for a cached version first
$cached = get_transient( 'smyles_cached_job_titles' );
if ( false !== $cached ) {
$section_data['fields'][ $field_id ]['data_source_options'] = $cached;
continue;
}
$args = array(
'posts_per_page' => - 1,
'post_type' => 'job_listing',
'post_status' => 'publish',
);
$posts = get_posts( $args );
$post_names = wp_list_pluck( $posts, 'post_title' );
$unique_post_names = array_unique( $post_names );
$data_source_options = array();
foreach ( $unique_post_names as $post_name ) {
$data_source_options[] = array(
'label' => $post_name,
'value' => $post_name
);
}
// Cache the result
set_transient( 'smyles_cached_job_titles', $data_source_options, HOUR_IN_SECONDS );
$section_data['fields'][ $field_id ]['data_source_options'] = $data_source_options;
}
}
return $section_data;
}
add_filter( 'search_and_filtering_sections_get_section', 'smyles_populate_post_titles', 10, 3 );
// Clear the cache when a job_listing post is updated, created, or deleted
function smyles_clear_job_titles_cache( $post_id ) {
// If this is just a revision, don't clear the cache
if ( wp_is_post_revision( $post_id ) ) {
return;
}
// Check the post type
$post_type = get_post_type( $post_id );
if ( 'job_listing' === $post_type ) {
delete_transient( 'smyles_cached_job_titles' );
}
}
add_action( 'save_post', 'smyles_clear_job_titles_cache' );
add_action( 'deleted_post', 'smyles_clear_job_titles_cache' );
add_action( 'trashed_post', 'smyles_clear_job_titles_cache' );
add_action( 'untrashed_post', 'smyles_clear_job_titles_cache' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment