在Wordpress页面的发布/更新上运行代码


Run code on publish/update of Wordpress page

我用Wordpress建立了一个网站。

我有一个包含以下代码的模板,它正在对地址进行地理编码并将结果保存到新数据库中。

然后我有另一个模板,可以从新数据库中读取所有纬度/液化天然气,并在谷歌地图上绘制数百个标记。

问题是地理编码仅在有人访问页面时发生。这会产生几个问题 - 1)每次有人访问页面时,它都会进行地理编码。2)它仅在有人访问页面时进行地理编码!

有没有办法在WordPress发布/更新页面时运行此代码一次?

本节从Wordpress获取公司信息并将其插入数据库:

    $company = get_field('company_name');
    $address = get_field('address');
    $city = get_field('city');
    $post_code = get_field('post_code');
    $sql = sprintf("select count('x') as cnt from markers where `name` = '%s'", mysql_real_escape_string($company));
    $row_dup = mysql_fetch_assoc(mysql_query($sql,$con));
    if ($row_dup['cnt'] == 0) {
        mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
}
wp_reset_query();

以下是完整代码:

  <?php
    require("database.php");
    // Opens a connection to a MySQL server
    $con = mysql_connect("localhost", $username, $password);
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("medicom_wp", $con);

        $company = get_field('company_name');
        $address = get_field('address');
        $city = get_field('city');
        $post_code = get_field('post_code');
        $sql = sprintf("select count('x') as cnt from markers where `name` = '%s'", mysql_real_escape_string($company));
        $row_dup = mysql_fetch_assoc(mysql_query($sql,$con));
        if ($row_dup['cnt'] == 0) {
            mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
    }
    wp_reset_query();

    define("MAPS_HOST", "maps.google.com");
    define("KEY", "");
    // Opens a connection to a MySQL server
    $connection = mysql_connect("localhost", $username, $password);
    if (!$connection) {
      die("Not connected : " . mysql_error());
    }
    // Set the active MySQL database
    $db_selected = mysql_select_db($database, $connection);
    if (!$db_selected) {
      die("Can''t use db : " . mysql_error());
    }
    // Select all the rows in the markers table
    $query = "SELECT * FROM markers WHERE 1";
    $result = mysql_query($query);
    if (!$result) {
      die("Invalid query: " . mysql_error());
    }
    // Initialize delay in geocode speed
    $delay = 0;
    $base_url = "http://" . MAPS_HOST . "/maps/geo?output=xml" . "&key=" . KEY;
    // Iterate through the rows, geocoding each address
    while ($row = @mysql_fetch_assoc($result)) {
      $geocode_pending = true;
      while ($geocode_pending) {
        $address = $row["address"];
        $id = $row["id"];
        $request_url = $base_url . "&q=" . urlencode($address);
        $xml = simplexml_load_file($request_url) or die("url not loading");
        $status = $xml->Response->Status->code;
        if (strcmp($status, "200") == 0) {
          // Successful geocode
          $geocode_pending = false;
          $coordinates = $xml->Response->Placemark->Point->coordinates;
          $coordinatesSplit = split(",", $coordinates);
          // Format: Longitude, Latitude, Altitude
          $lat = $coordinatesSplit[1];
          $lng = $coordinatesSplit[0];
          $query = sprintf("UPDATE markers " .
                 " SET lat = '%s', lng = '%s' " .
                 " WHERE id = '%s' LIMIT 1;",
                 mysql_real_escape_string($lat),
                 mysql_real_escape_string($lng),
                 mysql_real_escape_string($id));
          $update_result = mysql_query($query);
          if (!$update_result) {
            die("Invalid query: " . mysql_error());
          }
        } else if (strcmp($status, "620") == 0) {
          // sent geocodes too fast
          $delay += 1000;
        } else {
          // failure to geocode
          $geocode_pending = false;
          echo "Address " . $address . " failed to geocoded. ";
          echo "Received status " . $status . "
    'n";
        }
        usleep($delay);
      }
    }
    ?>      

一般来说:

在插件(或位于主题中的文件函数.php中),您有以下代码:

add_action('publish_post', function($post_id) {
  // Here you have some code that finds out the geocode data
  // then you attach it to this post as a meta value
  update_post_meta($post_id, 'my_geocode', $geo_data);
});

然后在您的模板文件(单个.php)中,您将得到如下内容:

$geo_data = get_post_meta($post->ID, 'my_geocode', true);
if( $geo_data ) {
  get_template_part('geocode');
}

或者,如果您想保持模板文件干净,您可以添加操作"the_content"在文件函数中.php位于主题目录(或插件文件中)

add_action('the_content', function() {
  if( is_singular() ) {
    global $post;
    $geo_data = get_post_meta($post->ID, 'my_geocode', true);
    if( $geo_data ) {
      get_template_part('geocode');
    }   
  }
}); 

做一个谷歌搜索,比如"wordpress add_action"。Wordpress可以让你"收听"wordpress中发生的不同事件。在您的情况下,我认为您可以使用名为"update_post"的操作。