Get maximum number of attached fields to any post

In a recent project I needed to get the maximum number of attached files to any post. The files were of course added to my posts by using Simple Fields and a repeatable field group.

Since this was the first time I’ve ever needed to do this, there was no built in functions for this.

Anyway, turned out to be pretty straightforward. The solution for me was this:


// The field with the files has the slug "document_attachment_file"
// and it belongs to a field group with the slug "document_attachments"

// First get some meta information about the field I want to check
$field_info = $sf->get_field_by_slug("document_attachment_file", "document_attachments");

// Get the name of the meta key that is used to store the value in wordpress own custom fields system
$file_meta_key = $sf->get_meta_key($field_info["field_group"]["id"], $field_info["id"], 0)

// Remove the last number from the meta key
// (as get_meta_key defualt to returning the meta key for the first field)
// This converts the meta key from something like
// simple_fields_fieldGroupID_3_fieldID_0_numInSet_0
// to
// _simple_fields_fieldGroupID_3_fieldID_0_numInSet_
$file_meta_key = preg_replace(‘/[0-9]+$/’, "", $one_term_meta_keys["file_meta_key"]);

// Make a sql query that gets all the meta rows containing our meta key,
// ordering them by highest to lowest, and returning only the first one = the highest one
$sql = sprintf(‘
SELECT CONVERT (substring(meta_key, %2$d), SIGNED INTEGER) AS numinset
FROM wp_postmeta
WHERE meta_key LIKE "%1$s"
ORDER BY numinset DESC
‘, "$file_meta_key%", strlen($file_meta_key)+1 );

// And we’re done.
// $highest_numInSet contains the maximum number of files that are attached to my posts
$highest_numInSet = $wpdb->get_var($sql);


Leave a Reply