首页 文章

The_title()Wordpress在php脚本中使用

提问于
浏览
1

我正在尝试获取the_title();从wordpress页面在php脚本中使用它

我的代码:

<?php 
  global $post;
  $args = array( 'numberposts' => 10, 'category_name' => 'bin-o' );
  $posts = get_posts( $args );
  foreach( $posts as $post ): setup_postdata($post); ?>
    $project_name = the_title();
    $post_id = get_page_id('$project_name');
    var_dump($project_name);
?>

<a href="<?php echo get_site_url() . '/?p=' .  $post_id  ?>"><h1><?php the_title() ?></h1>
<?php the_content() ?></a>

functions.php:

<?php 

  // Get the id of a page by its name
  function get_page_id($page_name){
    global $wpdb;
    $page_name = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$page_name."'");
    return $page_name;
  }
?>

问题是它只在打印时给出了the_title() . 所以我不能使用the_title()将它用于php脚本,因为the_title将返回NULL

我该如何解决这个问题,以便我可以使用所请求的 Headers 在php脚本中进一步使用它

2 回答

  • 4

    你使用get_the_title() .

    许多wordpress in-loop函数都有相应的 get_ 版本,它们将返回值,而不是回显它 .

  • 1

    我现在用过这个:

    <?php
      $project_name = trim(ucfirst(get_the_title())); //The title of current post!
      $project_info = get_page_by_title($project_name);
      $project_id = $project_info->ID;
    ?>
    
    <a href="<?php echo get_site_url() . '/?p=' .  $project_id  ?>"><h1><?php the_title() ?></h1>
    <?php the_content() ?></a>
    

    project_info获取所有项目信息,project_id从项目信息中获取ID,并使用它来重定向到所需页面 . 所以我不再需要使用这些功能了

相关问题