是否在发布或更新时执行操作?

时间:2012-06-20 作者:Rob

如果帖子刚刚发布或更新,是否有办法只在模板上执行一部分代码?

我需要如何包装这些代码?

UPDATE:

我需要检查我的自定义帖子类型“members”是否已保存。我用来显示帖子的模板是单成员。php。

如果帖子已经保存,那么就在我的单身会员上。php模板,我需要调用get_template_part(\'geocode\'); - but only if the post has been saved.

I DON\'T WANT THIS TO HAPPEN IN THE ADMIN AREA, THIS NEEDS TO HAPPEN FRONT-END OF THE WEBSITE. OBVIOUSLY THE ONLY THING I WANT TO DO IN THE ADMIN AREA IS TO CLICK PUBLISH/UPDATE.

这是地理代码中的内容。php文件:

<?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);
  }
}


?>

2 个回复
SO网友:OriginalEXE

为什么不将其包装在post save\\u post和post\\u publish挂钩中?

这里有一些例子:http://codex.wordpress.org/Function_Reference/add_action

方法:将其添加到函数中。php文件:

function my_data_update () {
 $company = get_field(\'company_name\');
 $address = get_field(\'address\');
 $city = get_field(\'city\');
 $post_code = get_field(\'post_code\');
 //etc etc...
}
add_action(\'publish_post\', \'my_data_update\');
add_action(\'save_post\', \'my_data_update\');

SO网友:mrwweb

我最近使用了几乎完全相同的用例:

保存自定义帖子类型时,请检查是否存在某些元数据

正如@OriginalEXE所建议的,我使用了save_post hook. 我觉得你不需要publish_post:

save\\u post是在创建或更新帖子或页面时触发的操作,可以通过导入、帖子/页面编辑表单、xmlrpc或电子邮件发布。

还有一些注意事项:

请注意行动的优先级较低。我发现,将其保留为默认优先级后,它会查看以前保存的数据(这些数据是使用高级自定义字段保存的,看起来您正在使用这些字段)wp_remote_get() 具有更好的服务器支持的函数curlfile_get_contents. 它使用JSON(谷歌推荐)请求,而不是XMLfunctions.php:

/* function wc_add_latlong()
 * take address from post, geocode it, and save as a custom meta field
 * @parameter $post_id, id of the post being saved, passed by save_post hook
 * @returns nothing
 **************************************/
function wc_add_latlong( $post_id ) {
    // get the address from ACF field
    $address = get_field( \'wc_map_address\', $post_id );
    // Check to see if the post type is right, it\'s not a revision, and there is an address to geocode
    if( get_post_type( $post_id ) == \'wc_biz\' && !wp_is_post_revision( $post_id ) && $address ) {
        // call the geocoder class below
        $coords = geocoder::getLocation( $address );
        // split latLngObject with a comma and space
        $lat_long_string = $coords[\'lat\'] . \', \' . $coords[\'lng\'];
        // either add that value as a new post meta field OR update the existing one
        add_post_meta( $post_id, \'_wc_lat_long\', $lat_long_string, true ) || update_post_meta( $post_id, \'_wc_lat_long\', $lat_long_string );
    }
}
// This runs on the save_post hook
add_action( \'save_post\', \'wc_add_latlong\', 11 );

// Thank you Sergiy!
// http://erlycoder.com/45/php-server-side-geocoding-with-google-maps-api-v3
// a class to get the lat and long of an address _server-side_
class geocoder{
    // The base URL for a non-sensor json Google Geocode API request
    static private $url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=";

    static public function getLocation($address){
        // append URL-friendly address to base URL
        $url = self::$url.urlencode($address);
            // request the Geocode JSON object from Google
        $resp_json = wp_remote_get($url);
            // decode the body of the response
        $resp = json_decode( wp_remote_retrieve_body($resp_json), true );
            // make sure the remove_get was successful and it geocoded the address
        if( !is_wp_error( $resp_json ) && $resp[\'status\']=\'OK\' ) {
                // success! return the lat and long
            return $resp[\'results\'][0][\'geometry\'][\'location\'];
        }else{
                // we failed, return false
            return false;
        }
    }
}
更新:我已经对所有代码进行了注释,以便您能够理解发生了什么。你必须从那里适应它。

结束