7

我正在尝试将 URL GET 参数添加到我在 Wordpress 中的主菜单项之一(但我不知道如何)。因此,我的方法是检测菜单项上的单击事件,然后通过 ajax 将参数传递给我的 php 页面,该页面将根据需要处理传递的值。我的主要问题是,看看我的代码,为什么不工作?有没有更好的方法在 Wordpress 中做到这一点而不依赖于 javascript?

Here is the javascript:
    <script type="text/javascript">
        $(document).ready(function() {
            $("#menu-item-128").click(function() {
                $.ajax({
                    url: 'homepage.php',
                    type: "GET",
                    data: ({ homeclick = true }),
                    success: function() {
                       alert("success!");
                    }
                });
             });
         });
   </script>

Here is my PHP:
   $homeclick = $_GET['homeclick'];   

   if ( !isset( $_COOKIE['hs_user'] ) ) {
       get_header();
   } elseif (isset( $_COOKIE['hs_user'] ) && $homeclick == true ) {
       get_header();
   } else {
       // Do Something else
       header('Location: homepage-returning-users');        
   }
4

4 回答 4

10

The filter hook wp_get_nav_menu_items is used to manipulate the Nav Menus. The post_title used in the example is the title of the Menu (Navigation Label), not of the post/page.

home nav menu

Drop this code in your functions.php file, adjust the post_title and ?my_var=test to your needs. Note that better than functions is to create your own plugin.

add_filter( 'wp_get_nav_menu_items','nav_items', 11, 3 );

function nav_items( $items, $menu, $args ) 
{
    if( is_admin() )
        return $items;

    foreach( $items as $item ) 
    {
        if( 'Home' == $item->post_title)
            $item->url .= '?my_var=test';

    }
    return $items;
}
于 2013-09-11T14:41:51.090 回答
0

问题是您试图在 Ajax 调用中使用变量传递布尔值homeclick。GET 请求只使用文本,因为数据是通过 URL 传递的,所以如果你想要一个逻辑/布尔类型,你可以在文本中使用“true”和“false”,或者可能使用 0 和 1。还有一个语法错误,见下文。

尝试以下操作:

在您的 ajax 调用中,修复语法并将 homeclick 设置为“true”,如下所示 data: ({ homeclick: 'true' }),

并在您的 php 中,更改变量的 if 条件,$homeclick如下所示 $homeclick == 'true'

如果您想使用布尔值,您可能需要考虑使用 POST 方法。

于 2013-09-11T02:43:37.587 回答
0

我建议在外观>菜单中使用自定义菜单。它将帮助您使用获取参数保留自定义 URL。您可以在此处阅读Wordpress 菜单

于 2013-09-11T07:26:53.593 回答
0

这是来自 Brasofilo 的一个分支,非常适合我:(将此代码放在您的主题 functions.php 上)

// Transform title attributes to parameters
add_filter( 'wp_get_nav_menu_items','nav_items', 11, 3 );
function nav_items( $items, $menu, $args )
{
    if( is_admin() )
        return $items;
    foreach( $items as $item )
    {
    if ($item->attr_title != "") $item->url .= '#' . $item->attr_title;
    }
    return $items;
}

我在这里所做的是获取菜单项的属性并将它们转换为锚名称。这样我将拥有这种类型的 URL:www.domain.com/my-page#anchor1

在此之后,我只需要做一些 jQuery 魔术来跳转(渐进式向下滚动)到锚点。(代码笔)。

如果您看不到“标题属性”输入字段,请务必检查 Wordpress 管理菜单顶部“屏幕选项”按钮上的选项...

于 2019-10-22T21:35:47.567 回答