How to Get Post ID in WordPress

When you create a post or page in WordPress, the platform automatically assigns it an ID number or unique identifier. There are many scenarios in which you might want to get this WordPress post ID; for instance, if you need to exclude particular articles from a content grid or want to code a custom query.

Unfortunately, WordPress does not share the post ID openly, so you will need to follow a few steps to locate it. 😎

In this article, we will explain everything you need to know about how to find a post ID in WordPress – from a simple solution that only requires you to use your mouse to more advanced techniques to display IDs in columns and new dashboards. So, let’s jump right in!

What is post ID and why do you need It?

As we mentioned, post and page IDs are unique identifiers that WordPress uses to recognize specific content. For example, a plugin might need to know these details to include or exclude certain articles from a particular function. If you are a developer, you might also use these IDs to add custom code to your WordPress website or build shortcodes (most of them use post and page IDs as parameters, so it’s important to know them).

For example, if you want to target a specific page to change how your site looks and functions, you might write something like this:

if(is_single(POST_ID))

	//...

In this case, POST_ID is the unique identifier for the content you want to locate and use. Now, you would think finding this information would be easy, considering millions of people use (and adapt!) their WordPress theme on a daily basis. The truth is, finding post IDs is indeed relatively straightforward – but only if you know where to look!

Best ways to get WordPress post IDs

There are five main approaches you can use to view post IDs. Let’s go through each of them in a little more detail and see which is best for each case.

Option 1: Use the WordPress dashboard or URL

Using your WordPress dahboard is the easiest and quickest way to identify WordPress post IDs. To do this, just go to your menu options and click on Posts. This will show a list of posts on the right-hand side of your page.

To get their IDs, all you need to do is hover your mouse over the title. You will see the number at the bottom of your browser window:

Finding a post ID from the WordPress dashboard

If you have trouble seeing the ID this way, you can also click on the post to open it. This will take you to the Editor. The URL will also show the ID (62805 in the example below) in the navigation bar at the top of your web browser!

Locating a post ID from the browser address bar

One important thing to keep in mind is that the post address bar will show a different format when you edit an article compared to what your users see when they visit your site. This is because WordPress allows you to pick your own permalink structure, which means your address might not show IDs at all to your visitors. In fact, if you set up your permalinks correctly, it should not and will not publicly show the ID at all.

Option 2: Show your post IDs in the posts tab

This method is a little more advanced, but if you use IDs a lot, it’s worth considering. You can display post IDs directly on your Posts tab; all you need to do is edit the functions.php file to add a column title containing it.

The way you do this is by locating this file (which is usually under your wp-content/themes folder) and adding the following code to it:

function add_column( $columns )
	$columns['post_id_clmn'] = 'ID';
	return $columns;

add_filter('manage_posts_columns', 'add_column', 4);

function column_content( $column, $id )
	if( $column === 'post_id_clmn')
		 echo $id;

add_action('manage_posts_custom_column', 'column_content', 4, 2);

What this snippet will do is add a new ID column. Because the example above uses the “4” column, the ID will be shown in the 4th position starting from your left. You can, of course, adjust this code as you prefer.

post IDs in wp-admin

Option 3: Get your IDs using a PHP function

For developers, another easy way to fetch post IDs is to use actual PHP functions that have been built into WordPress from the start. These functions let you reference post IDs directly and do so in different places throughout your own custom code.

The function is actually quite straightforward:

get_the_id();

Of course, you can also find post ID numbers using the post slugs or post title, or even the post’s URL:

$mypost = get_page_by_path('post-slug', '', 'post');
$mypost->ID;
$mypost = get_page_by_title( 'The title of your post', '', 'post' );
$mypost->ID;
$mypost_id = url_to_postid( 'https://YOURWORDPRESSSITE.com/unique-post' );

Lastly, you can fetch IDs in a WordPress loop:

$id_query = new WP_Query( 'posts_per_page=6 );

while( $id_query-have_posts() ) : $id_query->the_post();
	$id_query->post->ID;
endwhile;

Although finding IDs this way can come in handy when you’re writing custom code, if all you need to do is get the number for just a few pages or posts, the other methods will work better.

Option 4: Use a plugin to display post IDs

If you don’t want to edit your functions.php file, something you can do instead is install a plugin that can display not just your post IDs but also the numbers for your pages, tags, categories, media files, and custom taxonomies and post types.

One good option is ShowIDs, a lightweight free plugin that doesn’t need any configuration. You just activate it, and it will automatically show your IDs on a column present on all admin pages.

Option 5: Locate your post data in the WordPress database

If you’re already familiar with the WordPress database, you might suspect that the post ID is also stored there. In fact, the database will contain everything related to your content, such as categories, tags, authors, dates, comments, and more.

To locate your post IDs using phpMyAdmin, all you need to do is:

  • Go to your hosting control panel (or cPanel – most hosts use it).
  • Click on Databases → phpMyAdmin.
  • Choose a database on the left side (most sites will only have one) and click Enter phpMyAdmin. Usually, the database that WordPress uses starts with wp_.
  • Find and click on wp_posts. You will see the post ID column in the fourth position.

Make sure you don’t change anything on your database unless you are familiar with the interface and understand the information that is stored here.

The post ID column within phpMyAdmin

Conclusion 🧐

As we have seen, finding your WordPress post and page IDs is easy if you know where to look.

Our recommended technique, if you need to locate a few of these unique identifiers, is to simply use the dashboard. This will be the fastest approach to finding IDs and the most straightforward solution if you want to avoid touching any code or installing any plugins on your site.

However, if you need to use IDs more frequently, you should consider adding an option that can display them in a column. You can do this by editing your functions.php file or by using a plugin (there are free ones that can do it for you). If you are a more advanced user, though, you can take advantage of your database to showcase this and more post information.

Free guide

5 Essential Tips to Speed Up
Your WordPress Site

Reduce your loading time by even 50-80%
just by following simple tips.

79 thoughts on “How to Get Post ID in WordPress

  • Amandanam

    Какие слова… супер, замечательная мысль
    лютики удивительно разнообразные полевые [url=http://whdf.ru/forum/user/55536/]http://whdf.ru/forum/user/55536/[/url], которые растут в азии, европе и северной америке с умеренным климатом.

  • Axods

    By providing us with your email address, you agree to Leafly’s Terms of Service and Privacy Policy. In order for us to help make your order as smooth as possible, you must have valid identification and be over the age of 21 to buy marijuana plants online. Fill out our contact form and a sales representative will contact you shortly after. You can also call or text us directly at (424) 427-4777The majority of orders placed, can be filled the same day. The Cannabis Control Act prohibits youth under 19 from possessing, consuming, or growing cannabis. The Act prohibits an adult from sharing or provide cannabis to a person under 19. The Act also prohibits an adult from allowing a person under 19 in their care from using cannabis. The Act allows police to seize and destroy cannabis small amounts from young people who are found to be breaking the laws. Police can fine or refer a young person to a program when found to be violating the Act.
    https://www.flatcure.com/community/profile/alonzorace63580/
    Roots maintain a relationship with other organisms to form a symbiotic community. For instance, some mycorrhizae grow hyphae that enter the roots. Other organisms are free-living or form a shield around the roots. These other organisms supply the roots with dissolved nutrients the plant requires, and the plant roots supply them with food, the sugars produced during photosynthesis. The soil should retain enough water for the plant to thrive, as the roots need that water, but it shouldn’t be so much that the roots cannot get enough oxygen either. By now, you’ve probably heard or read “grown in living soil” in several places. What seems like a trendy catchphrase in cannabis these past few years of legalization actually holds a significant amount of weight in the growing world. But what IS living soil and why does it matter? In this blog, we’ll be attacking these questions in the most straightforward, uncomplicated way, minus all the scientific jargon – just to clear your doubts and share the facts.

  • JohnLarry

    ПРИКОЛЬНЫЙ МУЛЬТЯГА
    лучшие https://ruanekdot.ru с возможностью подбора а также предпочтений торговых либо чаще всего занятных приколов.

  • Lauct

    These primers create moisturizing shields around each lash and contain oils, waxes and other smoothing ingredients that make mascara cling better. They prep the lashes for what is to come, giving them more volume, definition and sometimes curl. Some also contain nourishing ingredients like oils, waxes and collagen that keep eyelashes healthy and moisturized. If you want even more volume, shop for ones that contain mini fibers. For that consistently perfect cat eye look, turn to these extremely affordable magnetic eyelashes that come in a set of seven five and only cost less than $20. They arrive with magnetic eyeliner as well as application tools, and many reviewers wrote that they’re “easy to apply.” Plus, the set has over 16,000 five-star ratings.
    https://trevorbvqg814704.blogozz.com/16715559/cruelty-free-lengthening-mascara
    The same age-defying ingredients often found in your anti-aging creams and serums—hyaluronic acid, vitamin C—will help improve texture and tone while giving you great, even coverage. Our Dream Radiant Liquid Foundation contains hyaluronic acid and collagen and gives aging skin a plump, radiant look! The pros and cons of powder vs. liquid foundations are many, but a basic rule to follow is to start with your skin type. “Powder foundations are excellent for oily, combination skin or those who prefer a matte finish,” says makeup artist Derek Selby. “These are also the easiest and quickest formulas to apply. If you are a beginner or time-challenged, go for powder.” The best foundations for mature skin are boosted with skin-kind ingredients such as hyaluronic acid, which will lock moisture into the skin, preventing those cakey lines from developing at midday. Light-reflecting spheres will impart a soft-focus glow, while a dewy formulation will glide over rough-textured skin, concealing fine lines and wrinkles while brightening everything up.

  • KathrynHaime

    Приглашаем Ваше предприятие к взаимовыгодному сотрудничеству в сфере производства и поставки никелевого сплава [url=https://redmetsplav.ru/store/nikel1/zarubezhnye_materialy/erni/enicrmo-3/prutok_enicrmo-3/ ] Пруток ENiCrMo-3 [/url] и изделий из него.

    – Поставка катализаторов, и оксидов
    – Поставка изделий производственно-технического назначения (электрод).
    – Любые типоразмеры, изготовление по чертежам и спецификациям заказчика.

    [url=https://redmetsplav.ru/store/nikel1/zarubezhnye_materialy/erni/enicrmo-3/prutok_enicrmo-3/ ][img][/img][/url]

    [url=http://cottonforum.ru/index.php/item/200-zhilety-signalnye-ot-proizvoditelya]сплав[/url]
    [url=https://loovestorys.blogg.se/2012/july/bloggen-laggs-inte-ner.html]сплав[/url]
    0a04250

  • bitcoincasino

    I’ve been looking for photos and articles on this topic over the past few days due to a school assignment, bitcoincasino and I’m really happy to find a post with the material I was looking for! I bookmark and will come often! Thanks 😀

  • Spoitte

    zithromax clamydia And based on that, let s understand pathophysiology, why the heart fails, why you get cancer, why there s a pneumonia, and construct from step one, from the ground up, a new theory of medicine, a new kind of medicine that is based on rational precepts

  • twels

    Im konkreten Fall ging es um einen Mann, der zwischen Oktober 2018 und September 2020 insgesamt 18.000 Euro bei einem Online-Casino-Anbieter aus Malta verloren hatte, der zu diesem Zeitpunkt keine deutsche Glücksspiel-Konzession hatte. Daraufhin verklagte er das Casino und gewann vor dem Landgericht Traunstein, was das OLG München schon Ende September bestätigte und nun ausführlich begründete. Hintergrund ist, dass der Spielvertrag, der bei der Konto-Erstellung akzeptiert werden musste, überwiegend wegen Verstoßes gegen den Glücksspiel-Staatsvertrag nichtig ist. Das Casino darf die Einnahmen, die es mit Ihren Spielverlusten erzielt hat, nicht behalten, weil es an einer Rechtsgrundlage fehlt. Dies gilt nicht nur für Online Casinospiele, virtuelle Automatenspiele und Online Poker, sondern zumeist auch für Online Sportwetten.
    https://zoom-wiki.win/index.php?title=Euromillionen_gewinnränge
    In Deutschland hat die Sendung “Deal or No Deal” mit Linda de Mol für große Furore gesorgt und hat das Publikum fantastisch unterhalten. Wenn ihr die guten alten Zeiten vermisst und gerne mal wieder eine Runde spielen möchtet, solltet ihr den folgenden Testbericht aufmerksam lesen um alle Infos zum Gameplay zu erhalten. Unkontrolliertes Glücksspiel kann sich nachteilig auswirken und abhängig machen! Ergebnisse: 187. Genau: 187. Bearbeitungszeit: 206 ms. Wenn ihr den aktuellen Erfolg von Deal or No Deal etwas besser verstehen möchtet, dann müsst ihr euch dem Ursprung der Gameshow im Online Casino zu widmen. Denn bereits mehr als 15 Jahre bevor Deal or No Deal seinen Weg in die Online Casinos fand, galt die TV-Show in Deutschland, den Niederlanden und den USA als absoluter Kult. Insgesamt wurde die TV-Show in 38 Ländern weltweit ausgestrahlt.

  • lof

    Navigating to the best slots apps, or online casinos, paying real money is the first step you must take. You must carefully select which slots to play for real money since you don’t want to waste your deposit. Unfortunately, the symbols, 3D graphics, and animations are not factors affecting payouts. Instead, you must carefully consider the return to player rate (RTP) and the symbols’ payouts. You will massively increase your chances of winning real money at slots sites if you do so. Second, legal online casinos offer real money slots via sweepstakes gaming rules. These include LuckyLand Slots and Chumba Casino. You play with “sweeps cash,” which can be converted into US dollars and withdrawn into your bank account. To add a little more spice to our online casino we frequently come up with promotions that are tailormade for our gamers. This also ensures that the odd round of gaming is free of charge. Moreover, we occasionally organise exciting tournaments and leaderboard games that give you the chance to win bonuses or vouchers (more Twists) as well as level-ups. Become a gaming pro at GameTwist and show the other players online what you’re made of! New here? Then register and join in the fun with a great Twist Welcome Bonus.
    https://reignersworld.org/amogcamp2022/forums/profile/ryan1707561138/
    Per creare un conto ai casinò online Stellare, è necessario andare sul sito ufficiale CasinoStellare.com. Registrazione – procedura semplice e veloce che richiede 10 secondi. Si compone di diverse fasi. Il giocatore deve: Molte piattaforme online offrono versioni di Blackjack con 0,10 centesimi di euro di puntata, che rappresenta la puntata minima per tutti i casinò con indubbi vantaggi per i giocatori – Welcome bonus con deposito. Anche in questo caso si tratta di una promozione riservata ai giocatori che scelgono di iscriversi per la prima volta su un sito, anche se per accedere a questa offerta è necessario effettuare un deposito. Solitamente, si tratta di un bonus pari al 100% della prima ricarica. Prima di ottenerlo e utilizzarlo per puntare, però, consigliamo sempre di dare uno sguardo alla pagina Termini e Condizioni. All’interno, infatti, troverai le indicazioni da seguire per ottenere il bonus e, soprattutto, quali sono i requisiti di scommessa, ovvero il numero di volte che devi giocare l’importo ricevuto come bonus, ma con soldi veri.

  • Roulk

    — Жидкая РїРѕРґРІРѕРґРєР°. Дает более глубокий Рё интенсивный пигмент, чаще всего наносится довольно толстой линией. Ваш адрес email РЅРµ будет опубликован. Обязательные поля помечены * Ходила РЅР° прошлой неделе РЅР° семинар РїРѕ стрелкам… учились рисовать разными способами… изучали какие глаза бывают Рё какие РЅСѓР¶РЅС‹ для РЅРёС… стрелки… Еще РѕРґРёРЅ простой СЃРїРѕСЃРѕР± для новичков нарисовать стрелку – провести линию так, как получится, Р° затем подправить погрешности СЃ помощью ватной палочки, смоченной РІ РІРѕРґРµ. Средство демакияжа для этого РЅРµ подойдет — РѕРЅРѕ растворит пигмент РїРѕРґРІРѕРґРєРё, Рё стрелка потечет.
    https://medformei.com.br/community/profile/edmundodixson65/
    Скачайте приложение для iPhone чтобы быть РІ РєСѓСЂСЃРµ выгодных предложений Хотите драматичные стрелки или эффект дымки РЅР° глазах? РџРѕРґРІРѕРґРєР° РѕС‚ Maybelline идеально РїРѕРґС…РѕРґРёС‚ для этих целей. Гелевую текстуру надо наносить кисточкой (РјРѕР¶РЅРѕ РЅРµ тратиться, идет РІ комплекте СЃ пигментом). Рисуйте любые линии, делайте растушевки! РЎ непривычки может быть долго, РЅРѕ визажисты оценят. Р’ составе есть СѓС…РѕРґРѕРІРѕР№ компонент — экстракт Алое Вера. РЎ РЅРёРј Ваши глаза РЅРµ почувствуют раздражения.

  • Foogy

    ニンテンドー3DS コインを稼ぎたい方は、ルーレットでジャックポットを狙いましょう。他のゲームに比べジャックポットが狙いやすく、低リスクでコインを稼げます。また、事前に「成金べシムの挑戦状」を受けておくと、並行してクエスト攻略を行えます。 これが夕食だったらブチギレますか? グロッタの町でスペシャルルーレットステージが解放後、 半日程度もあれば、カジノのコインを9,999,999枚(カンスト)させることができるかと思います。 ルーレットで一番効率が良い稼ぎかたはジャックポットを狙うことです。一回のジャックポットで100万枚のコインが獲得できるため、圧倒的なコイン稼ぎ効率を誇ります。
    https://cashjcfo987777.fitnell.com/56798966/ps2-ドラクエ8カジノ
    どういうわけか、この“マーケティング”がフィルに悪いイメージをあたえている。多くのテレビ視聴者からは、甘やかされた生意気なやつとして見られていて、彼の名前にはポーカーの「わるがき」のイメージがつきまとう。しかし、このイメージがテレビを触発したのだ。このイメージのおかげで、ポーカーが何百時間もテレビ放映されるようになった。プレイヤーが何らかの個性を見せなかったら、ここまでのポーカー報道はありえなかっただろう。 ※以下の感想・レビューは、株式会社ブックウォーカーの提供する「読書メーター」によるものです。

  • safetoto

    It’s really great. Thank you for providing a quality article. There is something you might be interested in. Do you know safetoto ? If you have more questions, please come to my site and check it out!

Leave a Reply

Your email address will not be published. Required fields are marked *