wordpress - id 改变变量
问题描述
我正在做一个项目,我上传一个文件并在短代码中使用它的路径。现在我已经将帖子的 ID 硬编码到我的代码中,但我想让它动态化,以便新帖子自动获得正确的简码。
<?php
global $wpdb;
$thepost = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = 5574" ) );
echo do_shortcode ('[sgpx gpx="'.'/wp-content/uploads/' . $thepost->meta_value . '"]');
?>
解决方案
脱离@Damocles 所说的,你真的在为你当前的道路设置麻烦。相反,有内置的 WordPress 函数可以抽象出数据库并利用强烈建议您使用的缓存。
// Get the current WordPress post
$the_post = get_post();
//If we have a value (there are cases where this will be empty)
if($the_post){
// Get the value from the post meta table by the current post's ID
$the_post_meta = get_post_meta($the_post->ID, 'YOUR_META_KEY_HERE', true);
// Double-check that we have a value
if($the_post_meta) {
// Finally, echo the shortcode
echo do_shortcode ('[sgpx gpx="'.'/wp-content/uploads/' . $the_post_meta . '"]');
}
}
有几种方法可以获取当前帖子,但这get_post()
是最常见的。但是,如果您处于自定义循环中,则可能需要进行相应调整。
要访问元数据,使用get_post_meta()
其中包括一些优化,包括使用缓存而不是数据库。
虽然肯定有例外,但一般来说,如果您正在使用 WordPress 并且发现自己正在编写 SQL 语句,那么使用核心函数几乎总是有更好、更安全、更快等的方法来完成它。
推荐阅读
- javascript - 表单提交后停止页面重定向到php文件
- typo3 - 如何在 TYPO3 中设置默认 colPos
- openstack-cinder - 显示所有项目的煤渣配额使用情况?
- mysql - MySQL - 复制或更新一个表中的更改行
- apache-kafka - kafka 的 Confluent 和 Spring 模式注册表
- javascript - 浏览器 | 如何要求以前由 Browserify 创建的模块?
- mysql - MySQL 查询优化 LEFT JOIN 和 DISTINCT
- javascript - 如何防止ios中的后滑反应本机
- python - python在if语句中引发异常
- r - 尽管 xpath 似乎是正确的,但找不到元素