Skip to content

Instantly share code, notes, and snippets.

@robertuniqid
Created January 8, 2019 11:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertuniqid/df12d0c91ac9dc748c9ee67fe27d58a8 to your computer and use it in GitHub Desktop.
Save robertuniqid/df12d0c91ac9dc748c9ee67fe27d58a8 to your computer and use it in GitHub Desktop.
PHP WordPress Example Nested parent->id mapping
<?php
/**
* If WordPress will ever work smoothly with procedures, we want to refactor this.
* @param $search_term
* @return array
*/
function example_nested_parent_map_search( $search_term ) {
global $wpdb;
$sql = 'SELECT id,
parent_id
FROM `your-table`
WHERE content LIKE "%' . $search_term . '%"';
$results = $wpdb->get_results( $sql );
if( empty( $results ) )
return [];
$response = [];
$required_parent_ids = [];
foreach( $results as $result ) {
if( !isset( $response[ $result->parent_id ] ) )
$response[ $result->parent_id ] = [];
$response[ $result->parent_id ][] = $result->id;
if( $result->parent_id != 0 )
$required_parent_ids[] = $result->parent_id;
}
if( empty( $required_parent_ids ) )
return $response;
while( !empty( $required_parent_ids ) ) {
$sql = 'SELECT id,
parent_id
FROM `your-table`
WHERE id IN (' . implode( ",", $required_parent_ids ) . ')';
$results = $wpdb->get_results( $sql );
if( empty( $results ) )
return $response;
$required_parent_ids = [];
foreach( $results as $result ) {
if( !isset( $response[ $result->parent_id ] ) )
$response[ $result->parent_id ] = [];
$response[ $result->parent_id ][] = $result->id;
if( $result->parent_id != 0 )
$required_parent_ids[] = $result->parent_id;
}
}
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment