本文介绍了如何在function.php文件中获取当前的post_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在function.php文件中的函数

This is my function in function.php file

  function getcity(){
    global $wpdb;

    if($_POST['state'])
            {
                $id=$_POST['state'];
                $district = get_post_meta(get_the_ID() , 'district', true);

                                     var_dump($district);
                $result=$wpdb->get_results("SELECT * FROM districts WHERE state_id='$id'");

                                                       foreach($result as $row) {
                                                             $district_name   = $row-
  >district_name;
                             $district_id     = $row->district_id;

                            echo '<option value="'.$district_id.'">'.$district_name.'</option>';


            }
     }
   }
 add_action("wp_ajax_nopriv_getcity", "getcity");
 add_action("wp_ajax_getcity", "getcity");

我想在此函数中获取当前帖子 ID 以显示选定的下拉值..

I want to get current post id in this function to display selected dropdown value..

推荐答案

请注意,$postget_queried_object_id() 在第一个查询被触发之前不起作用.因此,此选项仅在钩子 template_redirect 及更高版本中可用.但是functions.php 被包含得更早(在钩子after_setup_theme 之前)所以这不是一个解决方案.

Note that $post or get_queried_object_id() do not work until the first query was fired. So this options are available only at the hook template_redirect and later. But functions.php is included much earlier (before the hook after_setup_theme) so this isn't a solution.

一个几乎可以在任何地方工作的函数

A function that should work pretty much anywhere would be

$url = 'http://' . $_SERVER[ 'HTTP_HOST' ] . $_SERVER[ 'REQUEST_URI' ];
$current_post_id = url_to_postid( $url );

此处概述了挂钩执行顺序.

如果您的代码在 template_redirect 钩子之后执行,这些选项可能会更好:

If your code is executed after the template_redirect hook these option may be better:

global $post;
$id = $post->id;

$id = get_queried_object_id();

这篇关于如何在function.php文件中获取当前的post_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 02:35