我已经在Wordpress主题functions.php中编写了这段代码,但是is_page()不起作用。每次都会出现其他情况。我有 JS 解决方案,但要求是 PHP 解决方案。
add_action( 'wpcf7_before_send_mail', 'wpcf7_do_something_else_with_the_data', 90, 1 );
function wpcf7_do_something_else_with_the_data( $WPCF7_ContactForm ){
// Submission object, that generated when the user click the submit button.
$submission = WPCF7_Submission :: get_instance();
if ( $submission ){
$posted_data = $submission->get_posted_data();
if ( empty( $posted_data ) ){ return; }
// Got name data
$name_data = $posted_data['your-name'];
if( is_page( 41235 ) ) {
// Do my code with this name
$changed_name = 'something with is page condition';
} else {
// Do my code with this name
$changed_name = 'something is in else condition';
}
// Got e-mail text
$mail = $WPCF7_ContactForm->prop( 'mail' );
// Replace "[your-name]" field inside e-mail text
$new_mail = str_replace( '[your-name]', $changed_name, $mail );
// Set
$WPCF7_ContactForm->set_properties( array( 'mail' => $new_mail ) );
}
return $WPCF7_ContactForm;
}
尝试了所有可能的方法,多个函数,连接函数,全局变量等。 但没有解决办法。
这里有一个快速解决方案: 添加隐藏字段以获取页面/帖子 ID,然后执行其余操作:) 谢谢
add_action( 'wpcf7_init', 'wpcf7_new_form_tag' );
function wpcf7_new_form_tag() {
wpcf7_add_form_tag( 'post_id', function ( $tag ) {
return '<input type="hidden" value="'.get_the_id().'" name="post-id">';
} );
}
add_action( 'wpcf7_before_send_mail', 'wpcf7_do_something_else_with_the_data', 90, 1 );
function wpcf7_do_something_else_with_the_data( $WPCF7_ContactForm ){
// Submission object, that generated when the user click the submit button.
$submission = WPCF7_Submission :: get_instance();
if ( $submission ){
$posted_data = $submission->get_posted_data();
if ( empty( $posted_data ) ){ return; }
// Got name data
$name_data = $posted_data['your-name'];
$page_id = $posted_data['post-id'];
if( $page_id == 41235 ) {
// Do my code with this name
$changed_name = 'something with is page condition';
} else {
// Do my code with this name
$changed_name = 'something is in else condition';
}
// Got e-mail text
$mail = $WPCF7_ContactForm->prop( 'mail' );
// Replace "[your-name]" field inside e-mail text
$new_mail = str_replace( '[your-name]', $changed_name, $mail );
// Set
$WPCF7_ContactForm->set_properties( array( 'mail' => $new_mail ) );
}
return $WPCF7_ContactForm;
}