Non riesco a ottenere l'ID del post in functions.php?
Ho bisogno dell'ID del post corrente in una funzione che ho scritto in functions.php, ma non riesco a ottenerlo. Ho provato diversi metodi.
Come:
get_the_ID(); //restituisce false
global $post;
$id = $post->ID; //restituisce null
global $wp_query
$id =$wp_query->get_queried_object_id(); //restituisce 0
$url = 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
$id = url_to_postid($url); //restituisce 0
Sto usando l'ultima versione di WordPress. Cosa posso fare ora?
AGGIORNAMENTO: Ho bisogno dell'ID del post nella funzione qui sotto.
function em_change_form(){
$id = get_the_ID();
if(isset($_GET['reg_typ'])) {
$reg_type = $_GET['reg_typ'];
if($reg_type =='vln'){
update_post_meta($id,'custom_booking_form', 2);
} elseif ($reg_type == 'rsvp') {
update_post_meta($id,'custom_booking_form', 1);
}
}
}
add_action('init','em_change_form');
L'ID del post è disponibile dopo che la query è stata eseguita.
Il primo hook sicuro per ottenere l'ID del post è 'template_redirect'
.
Se puoi modificare la tua funzione per accettare un ID del post come argomento, in questo modo:
function em_change_form($id){
$reg_type = filter_input(INPUT_GET, 'reg_typ', FILTER_SANITIZE_STRING);
if($reg_type === 'vln'){
update_post_meta($id,'custom_booking_form', 2);
} elseif ($reg_type == 'rsvp') {
update_post_meta($id,'custom_booking_form', 1);
}
}
Puoi fare:
add_action('template_redirect', function() {
if (is_single()){
em_change_form(get_queried_object_id());
}
});
Ho usato get_queried_object_id()
per ottenere l'ID del post corrente della query.
Se hai assolutamente bisogno di chiamare la tua funzione su un hook iniziale come 'init'
, puoi usare url_to_postid()
, e home_url()
+ add_query_arg()
per ottenere l'URL corrente:
add_action('init', function() {
$url = home_url(add_query_arg(array()));
$id = url_to_postid($url);
if ($id) {
em_change_form($id);
}
});
Nota che il secondo metodo è meno performante perché url_to_postid()
forza WordPress a analizzare le regole di riscrittura, quindi se puoi, usa il primo metodo.
