首页 > 解决方案 > 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 . '"]'); 
?>

标签: wordpress

解决方案


脱离@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 语句,那么使用核心函数几乎总是有更好、更安全、更快等的方法来完成它。


推荐阅读