首页 > 解决方案 > 获取 URL 参数并传递给 Wordpress 中的表单选择

问题描述

我需要从 URL 中获取一个参数并根据该参数选择一个选项。

这是在我更新 Contact Form 7 插件之前有效的代码:

PHP:

if (isset($_GET['location'])) {
    $parameter = $_GET['location'];
    echo $parameter;
} else {
    // Fallback behaviour goes here
}

JS:

jQuery(document).ready(function($){
    $('#location').find('option[data-url=<?php echo $parameter; ?>]').attr('selected','selected');
});

WP代码:

<select onchange="location=this.value;" id="location">
    <option readonly>Select your location</option>

    <?php
    $args = array(
        'post_type'      => 'page',
        'posts_per_page' => -1,
        'post_parent'    => '8',
        'order'          => 'ASC',
        'orderby'        => 'ID'
        );
    $parent = new WP_Query( $args );
    if ( $parent->have_posts() ) : ?>
    <?php while ( $parent->have_posts() ) : $parent->the_post(); ?>

    <option value="<?php echo get_option('home'); ?>/meet-the-fleet/?location=<?php the_title(); ?>" data-url="<?php the_title(); ?>"><?php the_title(); ?></option>

    <?php endwhile; ?>
    <?php endif; ?>

</select>

上面的所有代码都可以解决问题,但是在该更新之后不再起作用,即使在这种情况下不用于 CF7 插件......只是用于独立选择。它可能与jQuery有关?

十分感谢!

标签: javascriptwordpressparametersparameter-passing

解决方案


似乎问题出在加载 jQuery 时。它需要在我的代码之前加载,而不是之后,购买我不明白为什么在 CF7 更新之前工作得很好......


推荐阅读