Monday

  • Reflecting on mistakes
  • Custom array serialization
  • Metadata API

Reflecting on Mistakes


I created one file as main plugin file and all other classes inside includes directory.

movie-library/
├── movie-library.php
└── includes/
    ├── movie.php
    └── person.php

So I put everything related to movie like CPT, Taxonomies and metaboxes in the movie.php and for person.php did the same.

This made the files hugs like about 1000 lines, which made it really hard to maintain all of that, so to fix it and make it more maintainable for me I spent some time to refactor everything and make the directory structure a little bit different.

movie-library/
├── movie-library.php
└── includes/
    ├── utils/
    ├── metaboxes/
    │   └── MovieMetaboxes.php
    ├── post-types/
    │   ├── Movie.php
    │   └── Person.php
    └── taxonomy/
        ├── MovieTaxonomy.php
        └── PersonTaxonomy.php

This made the whole structure little bit more maintainable.

Custom array serialization


The custom meta boxes allow users to select multiple options at a time, they are sent as an array and need to be stored in the database.

When I looke at the default serialization in WordPress, it is not much readable it looks like this

a:2:{i:1;a:0:{}s:12:"_multiwidget";i:1;}

Frankly this looks ugly, even though we will be getting the unserialized version of this.

I wanted to store the array in string like format but also be able to retreive them into the array for that I used below format

$arr = array(10,20,30);
$serialized = '[10,20,30]';

Then to retrive this string array, we have to

  • First remove the [ and ] from the string
  • Then Split the string by "," to get the array
  • After converting the array elements into integer values to display the selected we use strict equality.
/**
	 * Deserialize Array
	 *
	 * @param  mixed $string String retrieved from db.
	 * @return array
	 */
	public static function deserialize_array( $string ) : array {

		$string = trim( $directors, '[]' );
		$arr    = explode( ',', $directors );
		$arr    = array_map( 'intval', $directors );
		return $arr;

	}

Metadata API


Metadata API is simple and standard way to access metadata of an object in wordpress. Mostly we will use it to store metadata related to our Custom Post Types.

  • add_metadata()
  • delete_metedata()
  • update_metadata()
  • get_metadata()

Metadata API is really useful to retrieve the metadata, also in our custom metaboxes we use function of this API to create new meta key and values pairs or update them when user creates or updated a movie post.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *