error in wordpress insert into custom table value empty or null

i want to get title of all post from wordpress post and insert into a custom table but it always insert null value why

<?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'));
}
?>

Related posts

Leave a Reply

1 comment

  1. In your function call you’re not passing the post title as an argument.

    insert_p_now(the_permalink());
    

    It means that in your function

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

    The value of $a is equal to the_permalink() which isn’t your post_title of course.
    If all you want to do is store the post title in a custom array, perhaps this is what you’re looking for:

    <?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;
    
    ?>
    

    You can of course use a separate function if you’ll be reusing the “insert into custom table” functionality.

    Hope that helps!