taxonomy-advanced.php 2.22 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
<?php
// Prevent loading this file directly
defined( 'ABSPATH' ) || exit;
require_once WCQD_METABOX_FIELDS_DIR . 'taxonomy.php';

if ( ! class_exists( 'WCQD_METABOX_Taxonomy_Advanced_Field' ) )
{
	class WCQD_METABOX_Taxonomy_Advanced_Field extends WCQD_METABOX_Taxonomy_Field
	{
		/**
		 * Get meta values to save
		 * Save terms in custom field, no more by setting post terms
		 * Save in form of comma-separated IDs
		 *
		 * @param mixed $new
		 * @param mixed $old
		 * @param int   $post_id
		 * @param array $field
		 *
		 * @return string
		 */
		static function value( $new, $old, $post_id, $field )
		{
			return implode( ',', array_unique( $new ) );
		}

		/**
		 * Save meta value
		 *
		 * @param mixed $new
		 * @param mixed $old
		 * @param int   $post_id
		 * @param array $field
		 *
		 * @return string
		 */
		static function save( $new, $old, $post_id, $field )
		{
			if ( $new )
				update_post_meta( $post_id, $field['id'], $new );
			else
				delete_post_meta( $post_id, $field['id'] );
		}

		/**
		 * Standard meta retrieval
		 *
		 * @param int   $post_id
		 * @param bool  $saved
		 * @param array $field
		 *
		 * @return array
		 */
		static function meta( $post_id, $saved, $field )
		{
			$meta = get_post_meta( $post_id, $field['id'], true );
			$meta = array_map( 'intval', array_filter( explode( ',', $meta . ',' ) ) );

			return $meta;
		}

		/**
		 * Get the field value
		 * Return list of post term objects
		 *
		 * @param  array    $field   Field parameters
		 * @param  array    $args    Additional arguments. Rarely used. See specific fields for details
		 * @param  int|null $post_id Post ID. null for current post. Optional.
		 *
		 * @return array List of post term objects
		 */
		static function get_value( $field, $args = array(), $post_id = null )
		{
			if ( ! $post_id )
				$post_id = get_the_ID();

			$value = self::meta( $post_id, '', $field );

			// Allow to pass more arguments to "get_terms"
			$args  = wp_parse_args( array(
				'include'    => $value,
				'hide_empty' => false,
			), $args );
			$value = get_terms( $field['options']['taxonomy'], $args );

			// Get single value if necessary
			if ( ! $field['clone'] && ! $field['multiple'] )
			{
				$value = reset( $value );
			}
			return $value;
		}
	}
}