Override function with child themes functions.php

As I read the header, I try to change the function called by the parent theme in my child, I know that the child theme is configured to load in advance, so I'm curious if this is even possible?

My parent theme has a function called ajax_search_box () in which I want to change the request and I do not want to change the parent theme files in case I need to update it along the way .. what would be the best way to do this?

Also, for bonus points, how will I do this with the widget? Thanks in advance!

function SearchFilter($query) { // If 's' request variable is set but empty if (isset($_GET['s']) && empty($_GET['s']) && $query->is_main_query()){ $query->is_search = true; $query->is_home = false; } return $query; } add_filter('pre_get_posts','SearchFilter'); function ajax_search_box() { if (isset($_GET["q"])) { $q = $_GET["q"]; global $wpdb; $q = mysql_real_escape_string($q); $q = $wpdb->escape($q); $query = array( 'post_status' => 'publish', 'order' => 'DESC', 's' => $q ); $get_posts = new WP_Query; $posts = $get_posts->query( $query ); // Check if any posts were found. if ( ! $get_posts->post_count ) die(); //Create an array with the results foreach ( $posts as $post ) echo $post->post_title . "|" . $post->ID . "\n"; } die(); } // creating Ajax call for WordPress add_action( 'wp_ajax_nopriv_ajax_search_box', 'ajax_search_box' ); add_action( 'wp_ajax_ajax_search_box', 'ajax_search_box' ); 
+6
source share
2 answers

the parent theme should check if there is (function_exists ('ajax_search_box')), and if it does not exist, it will declare it.

If the parent theme checks to see if this function exists, you can declare it first and do what you want.

If the parent theme is not checked, contact the theme author to find out if they will forward this change for the next update .... and the code itself too. Thus, when the theme is updated, you will still be fine.

+5
source

Exit functions.php , write your own plugin .

 <?php /** * Plugin Name: Manipulate the Parent * Requires: PHP5.3+ */ add_action( 'after_setup_theme', function() { remove_filter( 'pre_get_posts','SearchFilter' ); // now add your own filter add_filter( 'pre_get_posts', 'your_callback_for_your_filter' ); }); function your_callback_for_your_filter() { // do stuff } 
+2
source

Source: https://habr.com/ru/post/954726/


All Articles