【问题标题】:Getting wordpress post ID in functions.php在functions.php中获取wordpress帖子ID
【发布时间】: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?

标签: jquery wordpress forms


【解决方案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 传递的当前帖子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
  • 2010-12-04
  • 1970-01-01
  • 2013-10-11
  • 2017-04-23
  • 1970-01-01
  • 2014-03-12
相关资源
最近更新 更多