wordpress插入自定义表时出错,值为空或null


error in wordpress insert into custom table value empty or null

我想从wordpress帖子中获得所有帖子的标题,并插入到自定义表中,但它总是插入空值,为什么

<?php
global $post;
$args = array( 'numberposts' => -1 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : 
setup_postdata( $post ); 
insert_p_now(the_permalink());
endforeach;
wp_reset_postdata(); 
function insert_p_now($a)
{
    global $wpdb;
    $wpdb->insert('wp_posttable', array('post_title' => $a), array('%s'));
}
?>

在函数调用中,您没有将文章标题作为参数传递。

insert_p_now(the_permalink());

这意味着在你的功能

function insert_p_now($a)
{
    global $wpdb;
    $wpdb->insert('wp_posttable', array('post_title' => $a), array('%s'));
}

$a的值等于the_permalink(),当然这不是您的post_title。如果你只想把文章标题存储在一个自定义数组中,也许这就是你想要的:

<?php
global $wpdb;
$args = array( 'numberposts' => -1 );
$allposts = get_posts( $args );
foreach ( $allposts as $curpost ) : 
   $wpdb->insert('wp_posttable', array('post_title' => $curpost->post_title), array('%s')); 
endforeach;
?>

如果要重用"插入自定义表"功能,当然可以使用单独的函数。

希望能有所帮助!