WordPress - 获取包含短代码页面的页面ID

时间:2016-03-18 16:52:54

标签: php wordpress

假设我有" myshortcode" 作为短代码。我已经使用[myshortcode]在wordpress页面(pageid = 1)中插入了这个短代码。

如何在代码文件中获取页面的ID?我搜索并得到了这个似乎给我ID的解决方案。

global $wpdb;

$PageID = $wpdb->get_var('SELECT ID FROM '.$table_prefix.'posts WHERE post_content LIKE "%[myshortcode]%" AND post_parent = 0');

但问题是它将页面ID作为字符串返回。所以我似乎无法在数字上使用它。

例如,如果我在wp_redirect中使用它,则会收到页面未正确重定向的错误。

我尝试了(int)$ PageID ,但似乎没有解决问题。

任何帮助?

1 个答案:

答案 0 :(得分:1)

我解决了。然而,我不确定问题是什么。就像我提到的,我在插件中工作。这是应该重定向的代码。

// This is in the plugin's Initialize function.
add_action( 'template_redirect', 'wc_custom_redirect_after_purchase' ); 

function wc_custom_redirect_after_purchase() {
    global $wp, $wpdb;

    $PageID = $wpdb->get_var('SELECT ID FROM '.$table_prefix.'posts WHERE post_content LIKE "%[myshortcode]%" AND post_parent = 0');

    if ( is_checkout() && ! empty( $wp->query_vars['order-received'] ) ) {
        $order_id  = absint( $wp->query_vars['order-received'] );
        $order_key = wc_clean( $_GET['key'] );

        /**
         * Replace {PAGE_ID} with the ID of your page
         */
        $redirect  = get_permalink($PageID);
        $redirect .= get_option( 'permalink_structure' ) === '' ? '&' : '?';
        $redirect .= 'order=' . $order_id . '&key=' . $order_key. '&noredirect=1';
            wp_redirect( $redirect );       
        exit;
    }
}

我不确定问题是什么,但我总是以无尽的方式获得页面重定向。然后我在网上冲浪,发现" Page没有正确重定向"可能意味着您的重定向功能始终重定向回页面本身。所以这是一个永无止境的循环。其中一个原因是传递给重定向函数的空值

我做了 var_dump($ PageID)和whola,它传递了null。

你一定以为我很坚决不去早点检查,但我做到了。我使用相同的代码并将其放在另一个文件中,我得到$ PageID = 1(正如我在我的问题中解释的那样)。不太确定为什么VERY SAME代码在我的插件文件中返回null。

我改变了这一行

$PageID = $wpdb->get_var('SELECT ID FROM '.$table_prefix.'posts WHERE post_content LIKE "%[myshortcode]%" AND post_parent = 0');

直接

$PageID = $wpdb->get_var('SELECT ID FROM '.$wpdb->prefix.'posts WHERE post_content LIKE "%[myshortcode]%" AND post_parent = 0');

是的,这次重定向成功了。

我仍然不确定为什么以前的$ PageID查询在其他文件中工作但在我的插件文件中没有。所以,我实际上并没有学到任何东西。它刚刚受到打击和试验,我很幸运。

希望有人指出实际原因。直到那时,我可以幸福地忍受它。感谢 Ren和Daniel 花时间回复。