-
-
Save pixelbart/cd4b3cdf2aab7736cf6c0d12fb686e48 to your computer and use it in GitHub Desktop.
WordPress: Erstellen von sortierbaren Adminspalten
This file contains 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 | |
add_action('admin_init', 'init_columns'); | |
/** | |
* Initialisiert die neue Spalte. | |
* | |
* @return void | |
*/ | |
function init_columns(): void | |
{ | |
global $pagenow; | |
if (is_admin() && 'edit.php' === $pagenow) { | |
// Hier bei den Hooks drauf achten, dass "mein_post_type" mit dem jeweiligen Post Type ersetzt wird | |
add_filter('manage_mein_post_type_posts_columns', 'register_columns'); | |
add_action('manage_mein_post_type_posts_custom_column', 'populate_columns', 10, 2); | |
add_filter('manage_edit-mein_post_type_sortable_columns', 'register_sortable_columns'); | |
add_action('pre_get_posts', 'sort_columns_query'); | |
} | |
} | |
/** | |
* Registriert die neue Spalte, direkt nach der "Titel"-Spalte. | |
* | |
* @param array $defaults | |
* | |
* @return array | |
*/ | |
function register_columns(array $defaults): array | |
{ | |
$columns = []; | |
foreach ($defaults as $key => $value): | |
$columns[$key] = $value; | |
// Eine Spalte direkt nach dem "Titel" | |
if ('title' === $key) { | |
// Die neue Spalte: key = id, value = Name | |
$columns['premium'] = 'Art'; | |
} | |
endforeach; | |
return $columns; | |
} | |
/** | |
* Bestimmt den Inhalt der neuen Spalte. | |
* | |
* @param string $column_name | |
* @param int $post_id | |
* | |
* @return void | |
*/ | |
function populate_columns(string $column_name, int $post_id): void | |
{ | |
// Wenn die Spalte "premium" aufgerufen wird | |
if ('premium' === $column_name) { | |
// Beispiel mit einem Meta-Feld "premium" | |
if (get_post_meta($post_id, 'premium', true)) { | |
echo 'Premium'; | |
} else { | |
echo '-'; | |
} | |
} | |
} | |
/** | |
* Registriert die sortierbare neue Spalte. | |
* | |
* @param array $columns | |
* | |
* @return array | |
*/ | |
function register_sortable_columns(array $columns): array | |
{ | |
$columns['premium'] = 'premium'; | |
return $columns; | |
} | |
/** | |
* Bestimmt wie die Inhalte sortiert werden sollen, wenn man auf die Spalte klickt. | |
* | |
* @param object $wp_query | |
* | |
* @return void | |
*/ | |
function sort_columns_query(object $wp_query): void | |
{ | |
if (!is_admin()) { | |
return; | |
} | |
$orderby = $wp_query->get('orderby'); | |
if ('premium' === $orderby) { | |
$meta_query = [ | |
'relation' => 'OR', | |
[ | |
'key' => 'premium', | |
'type' => 'NUMERIC', | |
], | |
]; | |
$wp_query->set('meta_query', $meta_query); | |
$wp_query->set('orderby', 'meta_value'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment