Skip to content

Instantly share code, notes, and snippets.

@isotrope
Last active March 5, 2020 20:55
Show Gist options
  • Save isotrope/498f0bcac8a3641401161da0dcb10416 to your computer and use it in GitHub Desktop.
Save isotrope/498f0bcac8a3641401161da0dcb10416 to your computer and use it in GitHub Desktop.
<?php
class Get_Words {
public static $meta_compiled_words = 'awesome_words_compiled';
public static $repeater_name_left = 'awesome_words_repeater_left';
public static $repeater_name_right = 'awesome_words_repeater_right';
public static $repeater_subfield = 'words';
public static $cpt = 'wordpack';
public function __construct() {
}
public function init() {
add_action( 'save_post', [ $this, 'compile_words' ], 10, 2 );
}
/*
* Since this one is a bit longer, let's keep the get_words easier to read by splitting up
* the "compiling" routine
*/
public static function compile_words( $post_id, $post ) {
// Only set for post_type = our cpt
if ( self::$cpt !== $post->post_type ) {
return;
}
$words = [
'left' => [],
'right' => [],
];
// whatever logic you need to compile it all into a nice array that you'll re-use or pass to JS
if ( function_exists( 'have_rows' ) && have_rows( self::$repeater_name_left, $post_id ) ) {
while ( have_rows( self::$repeater_name_left, $post_id ) ) {
the_row();
$words['left'][] = get_sub_field( self::$repeater_subfield );
}
}
// droite
if ( function_exists( 'have_rows' ) && have_rows( self::$repeater_name_right, $post_id ) ) {
while ( have_rows( self::$repeater_name_right, $post_id ) ) {
the_row();
$words['right'][] = get_sub_field( self::$repeater_subfield );
}
}
update_post_meta( $post_id, self::$meta_compiled_words, $words );
}
// Can simply call Get_Words::get_words() or Get_Words::get_words( $post_id ) anywhere
public static function get_words( $post_id = false ) {
if ( empty( $post_id ) ) {
global $post;
$post_id = $post->ID;
}
return get_post_meta( $post_id, self::$meta_compiled_words, true );
}
}
$get_words = new Get_Words();
$get_words->init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment