【问题标题】:Assigning Wordpress post information to PHP array and assign the php array value to javascript array FOR THIS REASON将 Wordpress 帖子信息分配给 PHP 数组,并将 php 数组值分配给 javascript 数组为此原因
【发布时间】:2015-07-14 19:59:00
【问题描述】:

使用 Wordpress 中的值从 PHP 到 Javascript

我希望下面的代码能解释我想要什么。

    <?php
    $title = array();
    $i=0;
    if ( have_posts() ) : while ( have_posts() ) : the_post(); 
    $title[i]=the_title();
    $link[i]=the_permalink();
    $i++;
    endwhile; else:  

    $title[0]="Welcome to my website.";
    $link[0]="/index.php";

    endif; 

    ?> 

    <script>

    var list=new Array();
    list[0]='<a href="<?php echo $link[0] ?>"><?php echo $title[0] ?></a>';
    list[1]='<a href="<?php echo $link[1] ?>"><?php echo $title[1] ?></a>';
    list[2]='<a href="<?php echo $link[2] ?>"><?php echo $title[2] ?></a>';
    list[3]='<a href="<?php echo $link[3] ?>"><?php echo $title[3] ?></a>';
    list[4]='<a href="<?php echo $link[4] ?>"><?php echo $title[4] ?></a>';

    </script>

我的需要是

  • 获取最新/流行的 5 篇文章标题及其永久链接
  • 然后将其分配给 javascript 变量,如上述代码或更好的代码
  • 为什么我需要这个

    我正在创建一个简单且有效的新闻网站 wordpress 模板。我使用了一个 javascript 代码(来自网络),它将显示我放入特定数组变量中的任何文本,例如滚动文本(以快讯/突发新闻风格)。

    现在我希望滚动文本能够随着最新的博客/新闻帖子动态更新,而不是像现在一样是静态的。

        ...
        var list=new Array();
        list[0]='<a href="This is manually typed news one.';
        list[1]='<a href="This is manually typed news two.';
        list[2]='This is manually typed news three.';
        list[3]='This is manually typed news four.';
        list[4]='This is manually typed news five.';
        ...
    

    参考

    我正在创建的网站暂时在这个地址上可用

    www.iamone.in/todaynewstv.

    看看 Flash News 部分 - 这就是我所说的。

    我从http://javascripts.vbarsan.com/ 获得了完整的 javascript 代码

    简而言之,我期望的输出是

    以滚动文本样式显示最新的 5 或 10 篇博文,无需手动更新。

    [抱歉,我这边有任何错误的沟通。希望你们理解我的问题。 ]

    谢谢。 :)

    【问题讨论】:

      标签: javascript php html wordpress content-management-system


      【解决方案1】:

      只需 json_encode 数组。这是一个例子:

      首先你得到你的帖子:

      $args = array(
          'posts_per_page'   => 5,
          'offset'           => 0,
          'post_status'      => 'publish'
      );
      $posts_array = get_posts( $args );
      

      然后你 json_encode 在脚本标签中。

      <script type="text/javascript">
              jQuery(function(){
                  var postArray = <?php echo json_encode($posts_array); ?>;
                  console.log(postArray);
                  for (e in postArray) {
                      var postInfo = postArray[e];
                      console.log(postInfo);
                      //how to get the title:
                      var postTitle = postInfo.post_title;
                  }
              });
          </script>
      

      控制台日志将显示您可以访问哪些数据。这是截图:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-24
        • 2012-08-05
        • 1970-01-01
        • 2023-03-04
        • 2012-10-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多