Come ottengo l'ID di un post (pagina o CPT) da un titolo o da uno slug?
-
-
Come stavi usando `get_page_by_title`ed èiltipo dipostpersonalizzatogerarchico,nonpenso che`get_page` (chiamato da `get_page_by_title`)funzioneràperi tipinongerarchici.How were you using `get_page_by_title` and is the custom post type hierarchal, i don't think `get_page`(called by `get_page_by_title`) will work for non-hierarchal types.
- 0
- 2011-03-06
- t31os
-
Sì,iltipo dipostpersonalizzatoin questionenon ègerarchico.Yes, the custom post type in question is non-hierachal.
- 0
- 2011-03-06
- jnthnclrk
-
Ignorail commentoprecedente sull'esseregerarchico,non dovrebbeimportare,come stavi chiamando `get_page_by_title`?Ignore previous comment regarding being hierarchal, that shouldn't matter, how were you calling `get_page_by_title`?
- 0
- 2011-03-06
- t31os
-
5 risposta
- voti
-
- 2011-03-06
puoi usare questafunzione che salta dagoogle "ottienipostpertitolo"
/** * Recupera unpost datoiltitolo. * * @ utilizza $ wpdb * * @param string $post_title Titolo dellapagina * @param string $post_typeposttype ('post','page','any customtype') * @param string $ output Facoltativo.Tipo di output.OBJECT,ARRAY_N o ARRAY_A. * @returnmisto */ funzioneget_post_by_title ($page_title,$post_type='post',$ output=OBJECT) { global $ wpdb; $post=$ wpdb- >get_var ($ wpdb- >prepare ("SELEZIONA ID DA $ wpdb- >posts WHEREpost_title=% s ANDpost_type=% s",$page_title,$post_type)); if ($post) returnget_post ($post,$ output); returnnull; } you can use this function that jumps by google "get post by title"
/** * Retrieve a post given its title. * * @uses $wpdb * * @param string $post_title Page title * @param string $post_type post type ('post','page','any custom type') * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. * @return mixed */ function get_post_by_title($page_title, $post_type ='post' , $output = OBJECT) { global $wpdb; $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type)); if ( $post ) return get_post($post, $output); return null; }
-
Finora sono riuscito aevitare di utilizzare le query DB,poichépreferisco utilizzare lefunzioni WP standard.È davvero l'unicomodoper ottenere ciò di cui hobisogno?So far I've managed to avoid using DB queries, as I prefer to use standard WP functions. Is this really the only way to achieve what I need?
- 1
- 2011-03-06
- jnthnclrk
-
Il codicepubblicato èpraticamente una copia diretta dellafunzione `get_page_by_title` [] (http://core.trac.wordpress.org/browser/tags/3.1/wp-includes/post.php#L3162),la differenzaprincipaleecco chefunzioneràperi tipinongerarchici,quindi vale lapena averne unonella raccolta difunzioni.The code posted is pretty much a direct copy of the `get_page_by_title` [function](http://core.trac.wordpress.org/browser/tags/3.1/wp-includes/post.php#L3162), the major difference here is that it'll work for non-hierarchal types, so it's one worth having in your function collection.
- 0
- 2011-03-06
- t31os
-
@t31os Non homai detto chefossemio,ho solo aggiuntoil $post_typepaeane sì,sta andando allamia collezione.@t31os I never said it was mine i only added the $post_type paean to it and yep its going to my collection.
- 0
- 2011-03-06
- Bainternet
-
Nonti stavo accusando diniente amico,semmai sto supportando latua risposta ..;) Haigiàilmio +1 .. :)I wasn't accusing you of anything mate, if anything i'm supporting your answer.. ;) You already got my +1.. :)
- 0
- 2011-03-06
- t31os
-
@t31os Lo so,è solo unbrutto scherzo :)@t31os I know ,its just a bad joke :)
- 0
- 2011-03-06
- Bainternet
-
In chemodo è diverso dalnativo `get_page_by_title ()`? .. `get_page ()` èpraticamente un alias di `get_post ()` Non vedo comeil cambiamento abbia unimpatto su qualcosa.How is this different from native `get_page_by_title()`?.. `get_page()` is pretty much alias of `get_post()` I don't see how change impact anything.
- 0
- 2011-03-06
- Rarst
-
@Rarst Ora che hai sottolineato che è lo stesso,non riesco a vedere la differenza.@Rarst Now that you pointed that out it is the same, i can't see the difference.
- 0
- 2011-03-06
- Bainternet
-
@t31os quindi doveentrain gioco la cosa _nongerarchica_ che hai citato se lafunzione èessenzialmente la stessa? ..@t31os so where does _non-hierarchical_ thing you mentioned comes into play if function is essentially same?..
- 0
- 2011-03-06
- Rarst
-
Non so cosa stavopensando questamattina,get_page chiamaget_post comunque,e non hoidea delperchépensavo cheget_pagefunzioni soloperi tipigerarchici,nonpenso che sia veromentre succede.Don't know what i was thinking this morning, get_page calls get_post anyway, and i have no clue why i thought get_page only works for hierarchal types, i don't think that's true as it happens.
- 0
- 2011-03-06
- t31os
-
Questopuòesserefattofacilmente con l'oggettopagina.Vedi lamia risposta di seguito.This can be done easily with the page object. See my answer below.
- 0
- 2017-07-29
- Phill Healey
-
- 2011-06-17
Timanca unparametro difunzione.Inserisci un valorenulloperil secondoparametro opzionale $ outpute questafunzione dovrebbefunzionareperte.
get_page_by_title('My post title', null, 'customposttype');
Mi sono appenaimbattutonello stessoproblemae l'aggiunta delnull lo ha risoltoperme.
You are missing a function parameter. Throw a null in for the second optional paramter $output and this function should work for you.
get_page_by_title('My post title', null, 'customposttype');
I just ran into the same issue and adding the null fixed it for me.
-
Quel "null" dovrebbeessere veramente "OBJECT"per chiarezza.Ma sì,essenzialmente stavainserendoiltipo dipost cometipo di outputtralasciandoiltipo di output.That `null` should really be `OBJECT` for clarity. But, yes he was essentially throwing the post type in as the output type by leaving out the output type.
- 0
- 2017-07-29
- Phill Healey
-
- 2011-06-17
Tendo aevitare le query dirette al database.Invece,utilizzo l'oggetto
WP_Query
per analizzare le coseperme.Questa è,fondamentalmente,unafunzione che utilizzoin uno deimiei temiper ottenere unpostbasato su un dato slug:
function get_post_id( $slug, $post_type ) { $query = new WP_Query( array( 'name' => $slug, 'post_type' => $post_type ) ); $query->the_post(); return get_the_ID(); }
Questo creerà una query utilizzando l'API WPper recuperare unpost di untipo specifico con un dato slug,eseguirà lenormalifunzioni di loop sul risultatoe restituirà l'ID delpost.Potresti anche usarloper restituire l'interopostmodificando unpo 'lafunzione,ma dipende date.
I tend to shy away from direct DB queries. Instead, I use the
WP_Query
object to parse things for me.This is, basically, a function I use in one of my themes to get a post based on a given slug:
function get_post_id( $slug, $post_type ) { $query = new WP_Query( array( 'name' => $slug, 'post_type' => $post_type ) ); $query->the_post(); return get_the_ID(); }
This will create a query using the WP API to fetch a post of a specific type with a given slug, will run the regular loop functions on the result, and return the ID of the post. You could also use it to return the entire post by modifying the function a bit, but that's up to you.
-
Invece di `$ query->the_post ()` che alterail cicloe interromperà qualsiasifunzione `get_the_xxx` dopo diesso,usapiuttosto: if ($ query-> have_posts ()) { restituire $ query->post [0] -> ID; } altro { return 0; }Instead of `$query->the_post()` which alters the loop and will disrupt any `get_the_xxx` functions after it, rather use: if ($query->have_posts()) { return $query->posts[0]->ID; } else { return 0; }
- 0
- 2015-12-14
- Mikepote
-
- 2017-07-29
Ormai ha qualche anno,ma viene ancora visualizzato quando lo cerchi su Google.Quindi,ecco unmodo sempliceperfarlo:
$page = get_page_by_title( 'my post title' );
o
$page = get_post_ID_by_title('my post title', OBJECT, 'customposttype');
Quindi utilizza l'oggetto $pageper acquisire l'ID:
$page->ID
This is a few years old now, but it still pops up when searching for this on Google. So, here's a simple way to do it:
$page = get_page_by_title( 'my post title' );
or
$page = get_post_ID_by_title('my post title', OBJECT, 'customposttype');
Then just use the $page object to grab the ID:
$page->ID
-
- 2018-02-03
Attualmente (WP> 4.9.2)troveraiiltuo "qualsiasi"post/pagina,ecc.pertitolo/slugin questomodo:
$page = get_posts( array( //'name' => 'your-post-slug', // by post slug 'title' => 'Your post title', // by post title 'post_type' => 'page' // post type of your preference ) ); if ($page = $page[0]) // First/lowest ID taken if many objects { // Then you do whatever is needed... // $id = $page->id; // $content = $page->post_content; // or $content = apply_filters('the_content', $page->post_content); // etc. }
Currently (WP >4.9.2) you'll find your "any" given post/page etc. by title/slug this way:
$page = get_posts( array( //'name' => 'your-post-slug', // by post slug 'title' => 'Your post title', // by post title 'post_type' => 'page' // post type of your preference ) ); if ($page = $page[0]) // First/lowest ID taken if many objects { // Then you do whatever is needed... // $id = $page->id; // $content = $page->post_content; // or $content = apply_filters('the_content', $page->post_content); // etc. }
Ho setacciatoil Codex,non sono riuscito afarfunzionareget_page_by_title ()e sonopiuttosto sorpreso chenon sembraesserci unafunzione WP standardper questo compito.
Devo ottenere l'ID di un determinato articolo/cpt opagina utilizzando lo slug deltitolo dell'articolo/dellapagina.Idealmente sto cercando quanto segue:
get_post_ID_by_title('My post title', 'customposttype');
Cosa dovreifare?