Skip to content

Instantly share code, notes, and snippets.

@wppunk
Created January 24, 2020 23:38
Show Gist options
  • Save wppunk/360040ba7df4e2dcf3e94415c4cdff08 to your computer and use it in GitHub Desktop.
Save wppunk/360040ba7df4e2dcf3e94415c4cdff08 to your computer and use it in GitHub Desktop.
Get cf7 form list
<?php
/**
* List all CF7 forms
*
* @package CF7_List
* @author Maksym Denysenko
* @link https://github.com/mdenisenko/
* @copyright Copyright © 2019
* @license GPL-2.0+
* @wordpress-theme
*/
/**
* Class CF7_List
*/
class CF7_List {
/**
* CF7_List constructor.
*/
public function __construct() {
add_action( 'save_post', [ $this, 'clear_cache' ], 10 );
}
/**
* Get CF7 form list
*
* @return array
*/
public function get_cf7_forms(): array {
global $wpdb;
$forms = wp_cache_get( 'cf7-forms' );
if ( empty( $forms ) ) {
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
$forms = $wpdb->get_results(
$wpdb->prepare(
'SELECT ID, post_title FROM ' . $wpdb->posts . ' WHERE post_type = %s', "wpcf7_contact_form"
)
);
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery
$forms = wp_list_pluck( $forms, 'post_title', 'ID' );
wp_cache_add( 'cf7-forms', $forms );
}
return $forms;
}
/**
* Delete CF7 forms cache
*
* @param int $post_id Post id.
* @param WP_Post $post Post.
*/
public function clear_cache( int $post_id, WP_Post $post ) {
if ( 'wpcf7_contact_form' === $post->post_type ) {
wp_cache_delete( 'cf7-forms' );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment