最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Move custom code out of theme's functions.php file

programmeradmin7浏览0评论

I have written code to use on a single page, but I've placed it in the theme's functions.php and created a javascript file and placed it in the theme's JS directory.

Recently, the theme was updated and functions.php was overwritten and JS file disappeared.

Where do I need to put this code so when the theme is updated, my code will not be lost?

functions.php:


add_action('wp_ajax_zip_search', 'zip_search');
add_action('wp_ajax_nopriv_zip_search', 'zip_search' );
function zip_search()
{
    global $wpdb;

    $zip = $_REQUEST["zip_code"];   


/**/

    $query = 'SELECT zone FROM Counties WHERE zip = %s';
    $zone = $wpdb->get_var( $wpdb->prepare($query, $zip) );

    $output = "<h1>".$zone."</h1>";
    $t_zone = $zone;
    $trimmed_zone = trim($t_zone);

    $query = 'SELECT * FROM Managers WHERE zone = %s;';
    $manager_info = $wpdb->get_row(  $wpdb->prepare($query, $trimmed_zone) );

    $output .= "<table style=\"width:100%\">" . 
                    "<tr>".
                        "<th>Zone Manager</th>".
                        "<th>Phone</th>".
                        "<th>Email Address</th>".
                    "</tr>" .
                    "<tr>" . 
                        "<td>" . $manager_info->first_name . " " . $manager_info->last_name  . "</td>" . 
                        "<td>" . $manager_info->phone_number . "</td>" . 
                        "<td>" . $manager_info->email_address .  "</td>" . 
                    "</tr>" .
                "</table>";

    $query = 'SELECT Region_Number FROM Zones WHERE Zone = %s';
    $region = $wpdb->get_var( $wpdb->prepare($query, $zone) );

    $query = 'SELECT * FROM Agblist WHERE Region_Number = %s';
    $results = $wpdb->get_results( $wpdb->prepare($query, $region) );
    
    $output .= "<table style=\"width:100%\">";
    
    $output .= "<tr>".
                "<th>Company Name</th>".
                "<th>Contact Info</th>".
                "<th>Channel</th>".
                "<th>Territory</th>".
               "</tr>";

    foreach( $results as $result ) 
    {
        $output .= "<tr>".
                        "<td>".$result->Company_Name."</td>".
                        "<td>".$result->Corp_Address_Line_1."</br>".$result->Corp_Address_Line_2."</br>".$result->Corp_City.", ".$result->Corp_State." ".$result->Corp_Zip_Code."</br>".$result->Office_Phone_1."</td>".
                        "<td>".$result->Channel."</td>".
                        "<td>".$result->Agent_Territory."</td>".
                    "</tr>";
    }
    //$output .= "<li>Result: ".$results."</li>";
    $output .= "</table>";
/**/
    //$output = "<p>here</p>";
    $response = array(
        'data' => $output,
    );

    wp_send_json_success($response);
}

add_action( 'wp_enqueue_scripts', 'my_load_scripts' );
function my_load_scripts() {

    // Enqueue javascript on the frontend.
    wp_enqueue_script(
        'zip_js',
        get_template_directory_uri() . '/js/zip_search.js',
        array('jquery')
    );

    // The wp_localize_script allows us to output the ajax_url path for our script to use.
    wp_localize_script(
        'zip_js',
        'myAjax',
        array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
    );

}

/js/zip_search.js:

jQuery(document).ready( function() {
   console.log("Document loaded!");
   jQuery("#AgentSearchButton").click( function(e) {
      console.log("Search button clicked");
      e.preventDefault(); 
      var zipCode = document.getElementById("AgentInputField").value;
      console.log("Zip code entered: " + zipCode);
      jQuery.ajax({
         type : "post",
         dataType : "json",
         url : myAjax.ajaxurl,
         data : {
             'action': "zip_search",
             'zip_code' : zipCode
         },
         success: function(response) {
            console.log(response.data);
            if(response.success) {
                console.log("response.type == success");
                jQuery("#results").html(response.data.data);
            }
            else {
                console.log("response.type == else");
                console.log(response.data);
            }
         },
        error: function(errorThrown){
            console.log("In error, error thrown!");
            console.log(errorThrown);
        }
      })
   })
});

I have written code to use on a single page, but I've placed it in the theme's functions.php and created a javascript file and placed it in the theme's JS directory.

Recently, the theme was updated and functions.php was overwritten and JS file disappeared.

Where do I need to put this code so when the theme is updated, my code will not be lost?

functions.php:


add_action('wp_ajax_zip_search', 'zip_search');
add_action('wp_ajax_nopriv_zip_search', 'zip_search' );
function zip_search()
{
    global $wpdb;

    $zip = $_REQUEST["zip_code"];   


/**/

    $query = 'SELECT zone FROM Counties WHERE zip = %s';
    $zone = $wpdb->get_var( $wpdb->prepare($query, $zip) );

    $output = "<h1>".$zone."</h1>";
    $t_zone = $zone;
    $trimmed_zone = trim($t_zone);

    $query = 'SELECT * FROM Managers WHERE zone = %s;';
    $manager_info = $wpdb->get_row(  $wpdb->prepare($query, $trimmed_zone) );

    $output .= "<table style=\"width:100%\">" . 
                    "<tr>".
                        "<th>Zone Manager</th>".
                        "<th>Phone</th>".
                        "<th>Email Address</th>".
                    "</tr>" .
                    "<tr>" . 
                        "<td>" . $manager_info->first_name . " " . $manager_info->last_name  . "</td>" . 
                        "<td>" . $manager_info->phone_number . "</td>" . 
                        "<td>" . $manager_info->email_address .  "</td>" . 
                    "</tr>" .
                "</table>";

    $query = 'SELECT Region_Number FROM Zones WHERE Zone = %s';
    $region = $wpdb->get_var( $wpdb->prepare($query, $zone) );

    $query = 'SELECT * FROM Agblist WHERE Region_Number = %s';
    $results = $wpdb->get_results( $wpdb->prepare($query, $region) );
    
    $output .= "<table style=\"width:100%\">";
    
    $output .= "<tr>".
                "<th>Company Name</th>".
                "<th>Contact Info</th>".
                "<th>Channel</th>".
                "<th>Territory</th>".
               "</tr>";

    foreach( $results as $result ) 
    {
        $output .= "<tr>".
                        "<td>".$result->Company_Name."</td>".
                        "<td>".$result->Corp_Address_Line_1."</br>".$result->Corp_Address_Line_2."</br>".$result->Corp_City.", ".$result->Corp_State." ".$result->Corp_Zip_Code."</br>".$result->Office_Phone_1."</td>".
                        "<td>".$result->Channel."</td>".
                        "<td>".$result->Agent_Territory."</td>".
                    "</tr>";
    }
    //$output .= "<li>Result: ".$results."</li>";
    $output .= "</table>";
/**/
    //$output = "<p>here</p>";
    $response = array(
        'data' => $output,
    );

    wp_send_json_success($response);
}

add_action( 'wp_enqueue_scripts', 'my_load_scripts' );
function my_load_scripts() {

    // Enqueue javascript on the frontend.
    wp_enqueue_script(
        'zip_js',
        get_template_directory_uri() . '/js/zip_search.js',
        array('jquery')
    );

    // The wp_localize_script allows us to output the ajax_url path for our script to use.
    wp_localize_script(
        'zip_js',
        'myAjax',
        array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
    );

}

/js/zip_search.js:

jQuery(document).ready( function() {
   console.log("Document loaded!");
   jQuery("#AgentSearchButton").click( function(e) {
      console.log("Search button clicked");
      e.preventDefault(); 
      var zipCode = document.getElementById("AgentInputField").value;
      console.log("Zip code entered: " + zipCode);
      jQuery.ajax({
         type : "post",
         dataType : "json",
         url : myAjax.ajaxurl,
         data : {
             'action': "zip_search",
             'zip_code' : zipCode
         },
         success: function(response) {
            console.log(response.data);
            if(response.success) {
                console.log("response.type == success");
                jQuery("#results").html(response.data.data);
            }
            else {
                console.log("response.type == else");
                console.log(response.data);
            }
         },
        error: function(errorThrown){
            console.log("In error, error thrown!");
            console.log(errorThrown);
        }
      })
   })
});
Share Improve this question asked Jul 23, 2020 at 15:56 Daniel NebertDaniel Nebert 431 silver badge7 bronze badges 4
  • 1 developer.wordpress/themes/advanced-topics/child-themes – cjbj Commented Jul 23, 2020 at 16:00
  • 3 To prevent future overrides you need to create a child theme, check the wordpress docs about this, heres a link – Buttered_Toast Commented Jul 23, 2020 at 16:00
  • 1 Thank you! I almost came back with, "done that, didn't work", but I have been massaging this code to work out the bugs, and previous posts I've made solved problems that I was having, and this last little bit was what I needed! Much appreciated! – Daniel Nebert Commented Jul 23, 2020 at 16:27
  • 2 You can also create a custom plugin if you want the code to continue working regardless of what theme is used. Sometimes for a one off function I prefer to build it as a plugin rather than go the child theme route. – Tony Djukic Commented Jul 23, 2020 at 16:36
Add a comment  | 

1 Answer 1

Reset to default 4

In previous questions you mentioned that you created a child theme and installed the multiple themes plugin so that you could put code on a specific page on your site. So you've been using child themes in a way that they weren't intended to be used.

Instead, think of a child theme as a transparency, a layer over the top of your theme. You create a child theme, and place custom code in it, then activate that child theme instead of the theme you were using. WP will load both themes, preferring the template files in the child theme.

This way, because all your changes are in the child theme, when the parent theme is updated no loss occurs.

发布评论

评论列表(0)

  1. 暂无评论