Created
January 8, 2019 11:07
-
-
Save robertuniqid/df12d0c91ac9dc748c9ee67fe27d58a8 to your computer and use it in GitHub Desktop.
PHP WordPress Example Nested parent->id mapping
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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