Bruk $wp_filter global variabel for å feilsøke actions og filters. Se prioriteringer og callback-funksjoner umiddelbart.
NB

Hvordan feilsøke WordPress hooks? (List alle actions/Filters)

5.00 /5 - (22 votes )
Sist verifisert: 1. mars 2026
Erfaring: 5+ års erfaring
Innholdsfortegnelse

WordPress kjører på Hooks (Actions og Filters). Noen ganger skjer uventede ting – innhold forsvinner, titler endres, stiler ødelegges. Du mistenker at en plugin forstyrrer, men hvilken?

Du må vite nøyaktig hvilke funksjoner som er knyttet til en bestemt hook (f.eks. the_content eller wp_head).

WordPress hook-systemet: Forstå fundamentet

WordPress sitt hook-system er det som gjør det utvidbart. Hver hovedfunksjon i WordPress fyrer av hooks, noe som lar plugins og temaer endre oppførsel uten å redigere kjernefiler.

To typer Hooks:

  1. Actions – Gjør noe på et bestemt punkt (f.eks. wp_head, the_content)
  2. Filters – Endre data før de brukes (f.eks. the_title, the_content)

Ved feilsøking må du se:

  • Hvilke funksjoner som er hooket
  • Deres prioriteringer (utførelsesrekkefølge)
  • Hvilken plugin/tema som la dem til
  • Navnene på callback-funksjonene

Den komplette feilsøkingssnutten

Legg til denne forbedrede funksjonen i din functions.php eller bruk den i en Must-Use plugin under utvikling:

/**
 * Inspiser WordPress hooks med detaljert informasjon
 *
 * @param string $hook_name Hooken som skal inspiseres (f.eks. 'the_content', 'wp_head')
 * @param bool $show_details Vis fullstendige callback-detaljer
 * @return void
 */
function wppoland_inspect_hook( $hook_name, $show_details = false ) {
    global $wp_filter;

    if ( ! isset( $wp_filter[ $hook_name ] ) ) {
        echo '<div style="background:#fff3cd; border:2px solid #ffc107; padding:15px; margin:20px 0;">';
        echo "<strong>Hook '$hook_name' har ingen tilkoblede funksjoner.</strong>";
        echo '</div>';
        return;
    }

    $hook_data = $wp_filter[ $hook_name ];

    echo '<div style="background:#fff; border:2px solid #dc3545; padding:20px; margin:20px 0; font-family:monospace; font-size:12px; max-width:100%; overflow-x:auto;">';
    echo "<h2 style='margin-top:0; color:#dc3545;'>Debugging Hook: <code>$hook_name</code></h2>";

    // Sorter etter prioritet
    ksort( $hook_data->callbacks );

    echo '<table style="width:100%; border-collapse:collapse;">';
    echo '<thead><tr style="background:#f8f9fa;"><th style="padding:8px; text-align:left; border:1px solid #dee2e6;">Prioritet</th><th style="padding:8px; text-align:left; border:1px solid #dee2e6;">Funksjon</th><th style="padding:8px; text-align:left; border:1px solid #dee2e6;">Kilde</th></tr></thead>';
    echo '<tbody>';

    foreach ( $hook_data->callbacks as $priority => $callbacks ) {
        foreach ( $callbacks as $callback ) {
            $function_name = 'Ukjent';
            $source_file = 'Ukjent';

            if ( is_string( $callback['function'] ) ) {
                $function_name = $callback['function'];
                if ( function_exists( $function_name ) ) {
                    $reflection = new ReflectionFunction( $function_name );
                    $source_file = $reflection->getFileName() . ':' . $reflection->getStartLine();
                }
            } elseif ( is_array( $callback['function'] ) ) {
                if ( is_object( $callback['function'][0] ) ) {
                    $function_name = get_class( $callback['function'][0] ) . '::' . $callback['function'][1];
                } else {
                    $function_name = $callback['function'][0] . '::' . $callback['function'][1];
                }

                try {
                    $reflection = new ReflectionMethod( $callback['function'][0], $callback['function'][1] );
                    $source_file = $reflection->getFileName() . ':' . $reflection->getStartLine();
                } catch ( ReflectionException $e ) {
                    $source_file = 'Kan ikke bestemme';
                }
            } elseif ( is_object( $callback['function'] ) ) {
                $function_name = 'Closure';
                $reflection = new ReflectionFunction( $callback['function'] );
                $source_file = $reflection->getFileName() . ':' . $reflection->getStartLine();
            }

            // Oppdag plugin/tema
            $source_type = 'Kjerne';
            if ( strpos( $source_file, 'wp-content/plugins' ) !== false ) {
                $source_type = 'Plugin';
                preg_match( '/plugins\/([^\/]+)/', $source_file, $matches );
                $plugin_name = isset( $matches[1] ) ? $matches[1] : 'Ukjent';
            } elseif ( strpos( $source_file, 'wp-content/themes' ) !== false ) {
                $source_type = 'Tema';
                preg_match( '/themes\/([^\/]+)/', $source_file, $matches );
                $plugin_name = isset( $matches[1] ) ? $matches[1] : 'Ukjent';
            } else {
                $plugin_name = 'WordPress';
            }

            echo '<tr style="border-bottom:1px solid #dee2e6;">';
            echo '<td style="padding:8px; border:1px solid #dee2e6;"><strong>' . esc_html( $priority ) . '</strong></td>';
            echo '<td style="padding:8px; border:1px solid #dee2e6;"><code>' . esc_html( $function_name ) . '</code></td>';
            echo '<td style="padding:8px; border:1px solid #dee2e6;"><span style="color:' . ( $source_type === 'Plugin' ? '#dc3545' : ( $source_type === 'Tema' ? '#0073aa' : '#28a745' ) ) . ';">' . esc_html( $source_type ) . '</span> - ' . esc_html( $plugin_name ) . '</td>';
            echo '</tr>';

            if ( $show_details ) {
                echo '<tr><td colspan="3" style="padding:4px 8px; font-size:11px; color:#666; border:1px solid #dee2e6;">';
                echo 'Fil: ' . esc_html( $source_file );
                echo '</td></tr>';
            }
        }
    }

    echo '</tbody></table>';
    echo '</div>';
}

// Eksempler på bruk:
// add_action( 'wp_footer', function(){ wppoland_inspect_hook('the_content'); } );
// add_action( 'wp_footer', function(){ wppoland_inspect_hook('wp_head', true); } ); // Med detaljer

Hvordan bruke feilsøkingsfunksjonen

Grunnleggende bruk

Legg dette til i din functions.php midlertidig:

// Inspiser the_content hook
add_action( 'wp_footer', function() {
    if ( current_user_can( 'manage_options' ) ) { // Kun for administratorer
        wppoland_inspect_hook( 'the_content' );
    }
} );

Besøk hvilken som helst side og rull til bunnteksten. Du vil se en detaljert tabell som viser alle funksjoner koblet til the_content.

Inspiser flere hooks

add_action( 'wp_footer', function() {
    if ( ! current_user_can( 'manage_options' ) ) return;

    $hooks_to_check = array( 'the_content', 'wp_head', 'the_title', 'excerpt_length' );

    foreach ( $hooks_to_check as $hook ) {
        wppoland_inspect_hook( $hook );
    }
} );

Inspiser med fulle detaljer

// Vis filstier og linjenumre
add_action( 'wp_footer', function() {
    if ( current_user_can( 'manage_options' ) ) {
        wppoland_inspect_hook( 'the_content', true ); // true = vis detaljer
    }
} );

Forstå utdataene

Utdataene viser en tabell med tre kolonner:

Prioritet kolonne

WordPress utfører hooks i prioritetsrekkefølge (lavere tall først). Standardprioritet er 10.

Vanlige prioriteringer:

  • 1-9: Tidlig utførelse (før standard)
  • 10: Standardprioritet
  • 11-99: Sen utførelse (etter standard)
  • 999: Veldig sent (nesten sist)

Eksempel:

Prioritet 5:  wpautop (legger til avsnitt)
Prioritet 10: do_shortcode (behandler snarveier)
Prioritet 20: custom_plugin_function (kjører sist)

Funksjon kolonne

Viser navnet på callback-funksjonen:

  • Strengfunksjoner: wpautop, do_shortcode
  • Klassemetoder: MyPlugin::process_content
  • Closures: Closure (anonyme funksjoner)

Kilde kolonne

Indikerer hvor hooken ble lagt til:

  • Kjerne: WordPress kjernefunksjoner
  • Plugin: Navn på plugin
  • Tema: Navn på tema

Vanlige feilsøkingsscenarioer

Scenario 1: Innhold forsvinner

Problem: Innleggsinnhold er tomt eller mangler.

Feilsøking:

wppoland_inspect_hook( 'the_content' );

Se etter:

  • Funksjoner som returnerer tomme strenger
  • Funksjoner med høy prioritet som kan overskrive innhold
  • Plugin-funksjoner som fjerner HTML

Scenario 2: Tittel endres uventet

Problem: Sidetitler endres av noe.

Feilsøking:

wppoland_inspect_hook( 'the_title' );

Se etter:

  • SEO-plugins som endrer titler
  • Oversettelsesplugins
  • Egendefinerte tittelfiltre

Scenario 3: Stiler ødelegges

Problem: CSS/JS lastes ikke inn riktig.

Feilsøking:

wppoland_inspect_hook( 'wp_head' );
wppoland_inspect_hook( 'wp_enqueue_scripts' );

Se etter:

  • Plugins som fjerner stilark
  • Konflikterende enqueue-prioriteringer
  • Skripter som lastes i feil rekkefølge

Avansert: Programmatisk hook-inspeksjon

Sjekk om spesifikk funksjon er hooket

function wppoland_is_function_hooked( $hook_name, $function_name ) {
    global $wp_filter;

    if ( ! isset( $wp_filter[ $hook_name ] ) ) {
        return false;
    }

    foreach ( $wp_filter[ $hook_name ]->callbacks as $priority => $callbacks ) {
        foreach ( $callbacks as $callback ) {
            if ( is_string( $callback['function'] ) && $callback['function'] === $function_name ) {
                return array( 'priority' => $priority, 'found' => true );
            }
            if ( is_array( $callback['function'] ) && $callback['function'][1] === $function_name ) {
                return array( 'priority' => $priority, 'found' => true );
            }
        }
    }

    return false;
}

// Bruk
if ( wppoland_is_function_hooked( 'the_content', 'wpautop' ) ) {
    echo 'wpautop er hooket til the_content';
}

Fjern spesifikk hook midlertidig

// Fjern en problematisk hook
remove_filter( 'the_content', 'problematic_function', 10 );

// Eller fjern alle hooks fra en plugin
global $wp_filter;
if ( isset( $wp_filter['the_content'] ) ) {
    foreach ( $wp_filter['the_content']->callbacks as $priority => $callbacks ) {
        foreach ( $callbacks as $callback ) {
            if ( strpos( $callback['function'], 'ProblemPlugin' ) !== false ) {
                remove_filter( 'the_content', $callback['function'], $priority );
            }
        }
    }
}

Moderne alternativ: Query monitor plugin

I 2026 er den beste måten å feilsøke hooks på å bruke Query Monitor-pluginen av John Blackbourn.

Hvorfor query monitor?

  1. Visuelt grensesnitt: Rent, søkbart tabell
  2. Filstier: Viser nøyaktige filplasseringer
  3. Komponentnavn: Identifiserer plugins/temaer
  4. Ytelsesdata: Viser kjøretid per hook
  5. Ingen kode nødvendig: GUI-basert feilsøking

Installasjon

## Via wp-CLI
wp plugin install query-monitor --activate

## Eller last ned fra WordPress.org

Bruk av query monitor

  1. Installer og aktiver Query Monitor
  2. Besøk hvilken som helst side på nettstedet ditt
  3. Se etter “QM”-ikonet i administrasjonslinjen
  4. Klikk på “Hooks & Actions”
  5. Søk etter hook-navnet ditt
  6. Se alle tilkoblede funksjoner med prioriteringer og kilder

Query monitor vs. Egendefinert snutt

Bruk Query Monitor når:

  • Du trenger en permanent feilsøkingsløsning
  • Du vil ha ytelsesmålinger
  • Du feilsøker flere hooks
  • Du foretrekker GUI fremfor kode

Bruk Egendefinert Snutt når:

  • Du trenger rask, engangs feilsøking
  • Du er i et utviklingsmiljø
  • Du vil sjekke hooks programmatisk
  • Query Monitor ikke er tilgjengelig

Beste praksis for hook-feilsøking

1. Feilsøk kun i utvikling

La aldri feilsøkingskode ligge i produksjon:

if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
    add_action( 'wp_footer', function() {
        wppoland_inspect_hook( 'the_content' );
    } );
}

2. Begrens til administratorer

Sjekk alltid brukertillatelser:

if ( current_user_can( 'manage_options' ) ) {
    // Vis debug info
}

3. Bruk beskrivende hook-navn

Når du lager egne hooks, bruk prefikser:

// Bra
do_action( 'wppoland_before_content' );

// Dårlig
do_action( 'before_content' );

4. Dokumenter dine hooks

/**
 * Fyres av før hovedinnholdsområdet
 *
 * @param string $content Innleggsinnholdet
 */
do_action( 'wppoland_before_content', $content );

Feilsøking av vanlige problemer

Problem: Hook vises ikke

Mulige årsaker:

  1. Hook har ikke fyrt av ennå (sjekk hook-timing)
  2. Betinget logikk hindrer hook i å fyre av
  3. Hook-navn er stavet feil

Løsning:

// Sjekk om hook eksisterer
if ( has_action( 'your_hook_name' ) ) {
    echo 'Hook eksisterer';
} else {
    echo 'Hook eksisterer ikke';
}

Problem: Funksjon kjører ikke

Mulige årsaker:

  1. Prioritetskonflikt
  2. Betinget logikk
  3. Hook fjernet av en annen plugin

Løsning:

// Sjekk gjeldende prioritet
$priority = has_filter( 'the_content', 'your_function' );
echo "Prioritet: $priority";

Avanserte Hook-Feilsøkingsteknikker

Bruk av WP Hook Iterator

For mer avansert inspeksjon kan du opprette en iterator som går gjennom alle registrerte hooks:

/**
 * List alle aktive hooks på siden
 *
 * @return void
 */
function wppoland_list_all_hooks() {
    global $wp_filter;

    echo '<div style="background:#1e1e1e; color:#d4d4d4; padding:20px; margin:20px 0; font-family:monospace; font-size:11px;">';
    echo '<h2 style="color:#569cd6;">Alle aktive WordPress Hooks</h2>';

    $hooks_by_type = array(
        'actions' => array(),
        'filters' => array()
    );

    // Kategoriser hooks
    foreach ( $wp_filter as $hook_name => $hook_data ) {
        if ( strpos( $hook_name, 'filter' ) !== false || strpos( $hook_name, '_filter' ) !== false ) {
            $hooks_by_type['filters'][$hook_name] = $hook_data;
        } else {
            $hooks_by_type['actions'][$hook_name] = $hook_data;
        }
    }

    // Vis Actions
    echo '<h3 style="color:#4ec9b0;">Actions (' . count( $hooks_by_type['actions'] ) . ')</h3>';
    echo '<ul style="list-style:none; padding:0;">';

    $i = 0;
    foreach ( $hooks_by_type['actions'] as $hook_name => $hook_data ) {
        if ( $i++ > 20 ) {
            echo '<li>... og ' . ( count( $hooks_by_type['actions'] ) - 20 ) . ' flere actions</li>';
            break;
        }
        $callback_count = 0;
        foreach ( $hook_data->callbacks as $callbacks ) {
            $callback_count += count( $callbacks );
        }
        echo '<li style="margin:4px 0;"><code style="color:#dcdcaa;">' . esc_html( $hook_name ) . '</code> (' . $callback_count . ' callbacks)</li>';
    }
    echo '</ul>';

    // Vis Filters
    echo '<h3 style="color:#4ec9b0;">Filters (' . count( $hooks_by_type['filters'] ) . ')</h3>';
    echo '<ul style="list-style:none; padding:0;">';

    $i = 0;
    foreach ( $hooks_by_type['filters'] as $hook_name => $hook_data ) {
        if ( $i++ > 20 ) {
            echo '<li>... og ' . ( count( $hooks_by_type['filters'] ) - 20 ) . ' flere filters</li>';
            break;
        }
        $callback_count = 0;
        foreach ( $hook_data->callbacks as $callbacks ) {
            $callback_count += count( $callbacks );
        }
        echo '<li style="margin:4px 0;"><code style="color:#dcdcaa;">' . esc_html( $hook_name ) . '</code> (' . $callback_count . ' callbacks)</li>';
    }
    echo '</ul>';

    echo '</div>';
}

// Bruk: add_action( 'wp_footer', 'wppoland_list_all_hooks' );

Performance-Profilering av Hooks

For å identifisere langsomme hooks kan du lage en profiler:

/**
 * Profilere hook-ytelse
 *
 * @param string $hook_name Hooken som skal profileres
 * @return array Ytelsesdata
 */
function wppoland_profile_hook( $hook_name ) {
    global $wp_filter;

    if ( ! isset( $wp_filter[ $hook_name ] ) ) {
        return array( 'error' => 'Hook not found' );
    }

    $results = array();

    foreach ( $wp_filter[ $hook_name ]->callbacks as $priority => $callbacks ) {
        foreach ( $callbacks as $index => $callback ) {
            $start_time = microtime( true );

            // Kjør hook (unntatt den faktiske funksjonen)
            $args = array();

            $end_time = microtime( true );
            $execution_time = ( $end_time - $start_time ) * 1000; // ms

            $function_name = 'Unknown';
            if ( is_string( $callback['function'] ) ) {
                $function_name = $callback['function'];
            } elseif ( is_array( $callback['function'] ) ) {
                $function_name = is_object( $callback['function'][0] )
                    ? get_class( $callback['function'][0] ) . '::' . $callback['function'][1]
                    : $callback['function'][0] . '::' . $callback['function'][1];
            } elseif ( is_object( $callback['function'] ) ) {
                $function_name = 'Closure';
            }

            $results[] = array(
                'priority' => $priority,
                'function' => $function_name,
                'estimated_cost' => $execution_time,
            );
        }
    }

    return $results;
}

Automatisk Konflikt-Deteksjon

Lag en funksjon som automatisk oppdager potensielle konflikter:

/**
 * Detekter hook-konflikter
 *
 * @return array Konflikter funnet
 */
function wppoland_detect_hook_conflicts() {
    global $wp_filter;

    $conflicts = array();

    foreach ( $wp_filter as $hook_name => $hook_data ) {
        $functions_by_name = array();

        foreach ( $hook_data->callbacks as $priority => $callbacks ) {
            foreach ( $callbacks as $callback ) {
                $func_key = 'unknown';

                if ( is_string( $callback['function'] ) ) {
                    $func_key = $callback['function'];
                } elseif ( is_array( $callback['function'] ) && isset( $callback['function'][1] ) ) {
                    $func_key = $callback['function'][1];
                } elseif ( is_object( $callback['function'] ) ) {
                    $func_key = 'closure_' . spl_object_id( $callback['function'] );
                }

                if ( isset( $functions_by_name[ $func_key ] ) ) {
                    // Samme funksjon hooket flere ganger
                    $conflicts[] = array(
                        'hook' => $hook_name,
                        'function' => $func_key,
                        'type' => 'duplicate',
                        'priorities' => array_merge( $functions_by_name[ $func_key ], array( $priority ) ),
                    );
                }

                $functions_by_name[ $func_key ][] = $priority;
            }
        }
    }

    return $conflicts;
}

// Vis konflikter
function wppoland_show_conflicts() {
    $conflicts = wppoland_detect_hook_conflicts();

    if ( empty( $conflicts ) ) {
        echo '<p>Ingen hook-konflikter oppdaget.</p>';
        return;
    }

    echo '<div style="background:#fff3cd; border:2px solid #ffc107; padding:15px; margin:20px 0;">';
    echo '<h3>Oppdaget Hook-Konflikter (' . count( $conflicts ) . ')</h3>';

    foreach ( $conflicts as $conflict ) {
        echo '<div style="margin:10px 0; padding:10px; background:#fff;">';
        echo '<strong>Hook:</strong> <code>' . esc_html( $conflict['hook'] ) . '</code><br>';
        echo '<strong>Funksjon:</strong> <code>' . esc_html( $conflict['function'] ) . '</code><br>';
        echo '<strong>Prioriteter:</strong> ' . implode( ', ', array_map( 'esc_html', $conflict['priorities'] ) );
        echo '</div>';
    }

    echo '</div>';
}

// Bruk: add_action( 'wp_footer', 'wppoland_show_conflicts' );

Hook Debugging i WP-CLI

For server-side debugging kan du bruke WP-CLI:

# List alle hooks som inneholder "content"
wp eval 'global $wp_filter; $hooks = array_filter(array_keys($wp_filter), function($h) { return strpos($h, "content") !== false; }); print_r($hooks);'

# Sjekk spesifikk hook
wp eval 'global $wp_filter; if(isset($wp_filter["the_content"])) { print_r($wp_filter["the_content"]->callbacks); } else { echo "Hook not found"; }'

#Installer Query Monitor for CLI
wp plugin install query-monitor --activate

Debugging av Dynamic Hooks

Noen hooks genereres dynamisk. Her er hvordan du håndterer dem:

/**
 * Inspiser dynamiske hooks
 *
 * Dynamiske hooks som 'the_content_{post_type}' krever spesiell håndtering
 */
function wppoland_inspect_dynamic_hooks() {
    global $wp_filter;

    $dynamic_hooks = array();

    foreach ( $wp_filter as $hook_name => $hook_data ) {
        // Sjekk for dynamiske mønstre
        if ( preg_match( '/^(the_content|the_title|wp_headers)_/', $hook_name ) ) {
            $dynamic_hooks[ $hook_name ] = $hook_data;
        }
    }

    if ( ! empty( $dynamic_hooks ) ) {
        echo '<div style="background:#e7f3ff; border:2px solid #0073aa; padding:15px; margin:20px 0;">';
        echo '<h3>Dynamic Hooks funnet (' . count( $dynamic_hooks ) . ')</h3>';

        foreach ( $dynamic_hooks as $hook_name => $hook_data ) {
            $callback_count = 0;
            foreach ( $hook_data->callbacks as $callbacks ) {
                $callback_count += count( $callbacks );
            }
            echo '<p><code>' . esc_html( $hook_name ) . '</code>: ' . $callback_count . ' callbacks</p>';
        }

        echo '</div>';
    }
}

// Vanlige dynamiske hooks:
// - 'the_content_{post_type}' - Kjører for spesifikk post type
// - 'the_title_{post_type}' - Tittel-filtrering for post type
// - 'single_template' - Template for enkeltposter
// - 'archive_template' - Template for arkiver

Hook Testing med WP_UnitTestCase

For enhetstesting av hooks:

/**
 * Eksempel på hook-testing
 */
class My_Hook_Test extends WP_UnitTestCase {

    function test_my_filter_modifies_content() {
        $post_id = $this->factory->post->create( array(
            'post_content' => 'Original content',
        ) );

        // Legg til filter
        add_filter( 'the_content', function( $content ) {
            return $content . ' Modified';
        } );

        // Hent post og sjekk
        $post = get_post( $post_id );
        $this->assertEquals( 'Original content Modified', apply_filters( 'the_content', $post->post_content ) );

        // Cleanup
        remove_all_filters( 'the_content' );
    }

    function test_hook_priority() {
        $results = array();

        add_action( 'test_hook', function() use ( &$results ) {
            $results[] = 'first';
        }, 5 );

        add_action( 'test_hook', function() use ( &$results ) {
            $results[] = 'second';
        }, 10 );

        add_action( 'test_hook', function() use ( &$results ) {
            $results[] = 'third';
        }, 15 );

        do_action( 'test_hook' );

        $this->assertEquals( array( 'first', 'second', 'third' ), $results );
    }
}

Logging av Hook-Kjøringer

For langvarig overvåking av hooks:

/**
 * Logg hook-kjøringer til fil
 */
function wppoland_hook_logger( $hook_name, $callback, $priority ) {
    $log_file = WP_CONTENT_DIR . '/debug-hook.log';

    $log_entry = sprintf(
        "[%s] Hook: %s | Priority: %d | Function: %s\n",
        current_time( 'mysql' ),
        $hook_name,
        $priority,
        is_callable( $callback ) ? 'callable' : gettype( $callback )
    );

    file_put_contents( $log_file, $log_entry, FILE_APPEND );
}

// Aktiver logging midlertidig
// add_action( 'all', 'wppoland_hook_logger', 10, 3 );

// Sjekk loggen
// tail -f wp-content/debug-hook.log

Hooks i WordPress 6.x og Fremtidige Versjoner

WordPress 6.x introduserer nye hook-funksjonaliteter:

  1. Block Editor Hooks – Flere hooks for Gutenberg-blokker
  2. REST API Hooks – Utvidet kontroll over REST-endepunkter
  3. Site Editor Hooks – Hooks for Full Site Editing (FSE)

Eksempel: Block Editor Hook

// Legg til metaboks i block editor
add_action( 'add_meta_boxes', function() {
    add_meta_box(
        'custom-metabox',
        'Custom Data',
        'render_custom_metabox',
        'post',
        'side'
    );
} );

// Bruk block editor hooks
add_action( 'enqueue_block_editor_assets', function() {
    wp_enqueue_script(
        'custom-editor-script',
        get_template_directory_uri() . '/editor.js',
        array( 'wp-blocks', 'wp-element' )
    );
} );

Vanlige Hook-Feil og Løsninger

Feil 1: Hook fungerer ikke i class-kontekst

// Feil: $this er ikke tilgjengelig i closure
class MyPlugin {
    function __construct() {
        add_action( 'init', function() {
            $this->init_plugin(); // Feil: $this er undefined
        });
    }

    function init_plugin() {
        // Kode
    }
}

// Riktig: Bruk use for å sende $this
class MyPlugin {
    function __construct() {
        add_action( 'init', function() {
            $this->init_plugin();
        });
    }
}

// Eller: Bruk klasse-metode direkte
class MyPlugin {
    function __construct() {
        add_action( 'init', array( $this, 'init_plugin' ) );
    }

    function init_plugin() {
        // Kode
    }
}

Feil 2: Prioritets-konflikt

// Problem: To funksjoner med samme prioritet
add_action( 'the_content', 'function_a', 10 );
add_action( 'the_content', 'function_b', 10 );

// Løsning: Bruk forskjellige prioriteringer
add_action( 'the_content', 'function_a', 10 );
add_action( 'the_content', 'function_b', 11 );

// Eller: Sjekk om hook allerede eksisterer
if ( ! has_action( 'the_content', 'function_a' ) ) {
    add_action( 'the_content', 'function_a', 10 );
}

Feil 3: Hook fjernet ved feil

// Problem: Fjerner feil hook-instans
remove_filter( 'the_content', 'my_callback', 10 );

// Løsning: Sjekk at hook eksisterer først
if ( has_filter( 'the_content', 'my_callback' ) ) {
    remove_filter( 'the_content', 'my_callback', 10 );
}

// Eller: Fjern alle instanser
remove_all_filters( 'the_content', 'my_callback' );

Sammendrag

Feilsøking av WordPress hooks er avgjørende for å forstå pluginkonflikter og temaproblemer. Den egendefinerte snutten gir detaljert informasjon om:

  • Hvilke funksjoner som er hooket
  • Deres utførelsesprioriteringer
  • Hvilke plugins/temaer som la dem til
  • Kildekode filplasseringer

Hovedpoenger:

  • Bruk $wp_filter global variabel for å inspisere hooks
  • Query Monitor er den beste GUI-løsningen for 2026
  • Begrens alltid feilsøking til utviklings-/adminbrukere
  • Forstå prioriteringer for å fikse ut førelsesrekkefølge problemer
  • Dokumenter dine egendefinerte hooks for vedlikeholdbarhet

Avanserte teknikker for profesjonelle:

  • Hook-iterasjon for å liste alle aktive hooks
  • Performance-profilering for å identifisere langsomme hooks
  • Automatisk konflikt-deteksjon
  • WP-CLI debugging for server-side feilsøking
  • Håndtering av dynamiske hooks
  • Enhetstesting med WP_UnitTestCase

Enten du bruker den egendefinerte snutten eller Query Monitor, er forståelse av WordPress hooks avgjørende for profesjonell WordPress-utvikling i 2026. Med disse avanserte teknikkene kan du raskt identifisere og løse selv de mest komplekse hook-relaterte problemene.

Hva er Hvordan feilsøke WordPress hooks? (List alle actions/Filters)?
Hvordan feilsøke WordPress hooks? (List alle actions/Filters) er et viktig aspekt ved administrasjon av WordPress-nettsider som bidrar til å forbedre nettstedets ytelse, sikkerhet og brukeropplevelse.
Hvordan fungerer Hvordan feilsøke WordPress hooks? (List alle actions/Filters)?
Hvordan feilsøke WordPress hooks? (List alle actions/Filters) innebærer å konfigurere ulike innstillinger og implementere beste praksis for å optimalisere din WordPress-nettside.
Hvorfor er Hvordan feilsøke WordPress hooks? (List alle actions/Filters) viktig for WordPress?
Hvordan feilsøke WordPress hooks? (List alle actions/Filters) er avgjørende fordi det direkte påvirker nettstedets søkemotorrangering, lastehastighet og generelle suksess.

Trenger du FAQ tilpasset bransje og marked? Vi lager en versjon som støtter dine forretningsmål.

Ta kontakt

Relaterte artikler