在functions.php中获取wordpress帖子ID

Posted

技术标签:

【中文标题】在functions.php中获取wordpress帖子ID【英文标题】:Getting wordpress post ID in functions.php 【发布时间】:2020-06-12 19:01:43 【问题描述】:

我在 Wordpress 中使用 JQuery 表单,提交时会调用 functions.php 文件中的函数。我需要能够访问该函数 (test_function) 中的帖子 ID。

(1) 我页面的 php.ini 中的 html 代码。这是调用“test_function”的形式。

<form autocomplete="off" id="form-id" enctype="multipart/form-data" action="<?php echo admin_url('admin-ajax.php')?>" method="post">
<input type="text" name="coords" placeholder="Coordinates" value="Some Value"/><br>
<input type="hidden" name="action" value="test_function"/>
<input type="submit" value="SUBMIT"/>
</form>

(2) 在我的functions.php中排队的外部JS文件

jQuery(document).ready(function() 
jQuery('#form-id').ajaxForm(
  success: function(response)
    console.log(response);
  ,
  error: function(response)
    console.log(response);
  ,
  resetForm:true
);
);

(3)functions.php中的test_function

function test_function()
    //do something here that needs the POST ID


add_action('wp_ajax_test_function', 'test_function');
add_action('wp_ajax_nopriv_test_function', 'test_function');

我不确定如何处理这个问题。 我已经尝试了以下所有 3 种方法,但都没有奏效。

global $post; $post_id = $post->ID;

global $wp_query; $post_id = $wp_query->get_queried_object_id();

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

【问题讨论】:

多个post id你想要哪个post? 【参考方案1】:
function get_ajax_posts() 
    // Query Arguments
    $args = array(
        'post_type' => array('post'),
        'post_status' => array('publish'),
        'posts_per_page' => -1,
        'order' => 'DESC'
    );

    // The Query
    $ajaxposts = get_posts( $args ); // changed to get_posts from wp_query, because `get_posts` returns an array

    echo json_encode( $ajaxposts );

    exit; // exit ajax call(or it will return useless information to the response)


// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');

【讨论】:

我不确定这与获取当前帖子的 id 有什么关系 你想要我通过 ajax 传递的当前帖子

以上是关于在functions.php中获取wordpress帖子ID的主要内容,如果未能解决你的问题,请参考以下文章

在functions.php中获取相关组的ACF字段值(通过Post Object)

如何获取functions.php中的当前帖子类型以便全局使用?

如何获取 woocommerce 订单的订单 ID 以在 functions.php 中的函数中使用?

在functions.php文件中调用它时,Wordpress没有从数据库获取值

PHP 在functions.php中启用hovercards

在 functions.php (WordPress) 中包含 ACF