admin管理员组

文章数量:1126449

Im looking at this tutorial.

But adding this code snippet to templates/single.html doesn't work.

<?php
$meta = get_post_meta( get_the_ID(), 'Sponsored Post' );
if( $meta[0] == 'Yes' ) {
?>
<p>This post is sponsored content, and we received a free copy of the product in order to conduct our review.</p>
<?php } ?>

Im looking at this tutorial.

But adding this code snippet to templates/single.html doesn't work.

<?php
$meta = get_post_meta( get_the_ID(), 'Sponsored Post' );
if( $meta[0] == 'Yes' ) {
?>
<p>This post is sponsored content, and we received a free copy of the product in order to conduct our review.</p>
<?php } ?>
Share Improve this question asked Apr 2, 2023 at 11:37 anjaneshanjanesh 1216 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

That tutorial is for a classic PHP theme, but 2023 is a modern block theme, it works completely differently. You can't put PHP in the HTML files in templates folder. You should think of these files as starting content, not PHP files, and any changes you make in the side editor are saved in the database as posts of type wp_template and wp_template_part that override these files.

If you want to insert PHP into a block theme it needs to be done via a block. The easiest route is by writing a short code, then using a shortcode block to insert it into the theme.


As a sidenote, be wary of these types of tutorials. It's telling you to add a custom field to let you set a post as a sponsored post, which on the surface sounds reasonable. The problem comes when you need to exclude sponsored posts from the homepage, or show a list of sponsored posts in a sidebar. Now you're forced to write more code to make that happen, and because the data is in a custom field ( post meta ) the performance is awful.

Instead a custom taxonomy, something you can generate code for by filling out a form on a WP generator site, would give you a proper GUI in the editor for free, template files (templates/taxonomy-name.html, archive pages that can show up in google sitemaps, REST API endpoints for javascript etc. This and the performance in a worst case scenario could be 100x faster.

If you need to filter/search/group posts that do or do not have this field then it should be a custom taxonomy. Perhaps a Post Features taxonomy with Sponsored/Featured etc.

Likewise, a category or tag would do the job better than a custom field.

本文标签: Adding PHP code to single template in 2023 edition of WordPress theme