admin管理员组

文章数量:1424910

Goal: I'm making a portfolio website in Wordpress. It's the first time that I have setup a Wordpress page by myself (I have done on internship but those were template-ish). I have seen this website that uses (what I think) Ajax to load its contents to the page. So for good practice I want to make myself one on the hardway. Until now with all the research I have learned more about wp_query and things, but not enough to fix this.

Problem:( I have changed my code before I posted this so it could be different again) I am a newb to ajax since this is my first time trying it. I have gathered information all around google and tried to mix it up with my code with my logic. I kinda understand things now but I really wouldnt know how I could get it to focus on the post ID i have clicked on. If I click on one of the posts now, it will retrieve all of the links if I do the_permalink(). I want the function to know which post it is clicking on so I can put the right content into the text-area in my html. I have tried ways to get the url with Jquery and turn it into the ID but that would need PHP again. I know that you can search up the post ID per page but that would hard code it right? I want it dynamic so if I make a new page it wouldnt need me to assign that ID via my editor. I'm really confused right now. I am trying to do this since 29/06/2019 (europe).

Here is my code for the Ajax. My site is live on kutuk.nl. if you need more code just tell me, Excuse me for the English its not my native language.

ajax-pagination.js

(function($) {

$(document).on( 'click', '.nav-link', function( event ) {

    event.preventDefault();
    var event = $(this).attr('href');
    $.ajax({
        url: ajaxpagination.ajaxurl,
        type: 'POST',
        data: {
            action: 'ajax_pagination',
        },
        success: function(data) {
            history.pushState(null, null, event);
            $( '.text-zone' ).html( data );
        }
    });
});
})(jQuery);

Functions.php

add_action( 'wp_ajax_nopriv_ajax_pagination', 'my_ajax_pagination' );
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_pagination' );
function my_ajax_pagination()

{
    $query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );

$query_vars['paged'] = $_POST['page'];

$posts = new WP_Query( $query_vars );
$GLOBALS['wp_query'] = $posts;



if( $posts->have_posts() ) :
while( $posts->have_posts() ):
    $posts->the_post(); ?>
        <h2>
            <?php
            the_permalink();
        ?>
        </h2>

    <?php endwhile;
    wp_reset_query();
    wp_reset_postdata();
endif;
    wp_die();
}

Localize the script

wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'query_vars' => json_encode( $wp_query->query ),
    ));

NOTE- I know that I havent used the query_vars in the localize_script but I am too confused right now. And that pagination probably is not the best naming for what I want( it was from a tutorial website).

UPDATE 14:40 04/06/2019 = I have found some kind of way to return the ID with $post_id = isset( $_POST['post_id'] ) ? $_POST['post_id'] : 'N/A'; and giving the AJAX data post_id: post_id. But the problem now is that it gives me an array array(1) { ["postId"]=> string(2) "22" }.

UPDATE 15:37 04/06/2019 = It worked I have only left the number, $post_id = isset($_POST['post_id']) ? $_POST['post_id'] : 'N/A'; echo $post_id["postId"];

UPDATE 16:01 04/06/2019 I have finally done it, apparently it was just 2 lines of code and I have spent just under a week on this. It was a journey that has learned me a lot. Thanks for the help people. If anyone needs the code I'll update this.

Goal: I'm making a portfolio website in Wordpress. It's the first time that I have setup a Wordpress page by myself (I have done on internship but those were template-ish). I have seen this website that uses (what I think) Ajax to load its contents to the page. So for good practice I want to make myself one on the hardway. Until now with all the research I have learned more about wp_query and things, but not enough to fix this.

Problem:( I have changed my code before I posted this so it could be different again) I am a newb to ajax since this is my first time trying it. I have gathered information all around google and tried to mix it up with my code with my logic. I kinda understand things now but I really wouldnt know how I could get it to focus on the post ID i have clicked on. If I click on one of the posts now, it will retrieve all of the links if I do the_permalink(). I want the function to know which post it is clicking on so I can put the right content into the text-area in my html. I have tried ways to get the url with Jquery and turn it into the ID but that would need PHP again. I know that you can search up the post ID per page but that would hard code it right? I want it dynamic so if I make a new page it wouldnt need me to assign that ID via my editor. I'm really confused right now. I am trying to do this since 29/06/2019 (europe).

Here is my code for the Ajax. My site is live on kutuk.nl. if you need more code just tell me, Excuse me for the English its not my native language.

ajax-pagination.js

(function($) {

$(document).on( 'click', '.nav-link', function( event ) {

    event.preventDefault();
    var event = $(this).attr('href');
    $.ajax({
        url: ajaxpagination.ajaxurl,
        type: 'POST',
        data: {
            action: 'ajax_pagination',
        },
        success: function(data) {
            history.pushState(null, null, event);
            $( '.text-zone' ).html( data );
        }
    });
});
})(jQuery);

Functions.php

add_action( 'wp_ajax_nopriv_ajax_pagination', 'my_ajax_pagination' );
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_pagination' );
function my_ajax_pagination()

{
    $query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );

$query_vars['paged'] = $_POST['page'];

$posts = new WP_Query( $query_vars );
$GLOBALS['wp_query'] = $posts;



if( $posts->have_posts() ) :
while( $posts->have_posts() ):
    $posts->the_post(); ?>
        <h2>
            <?php
            the_permalink();
        ?>
        </h2>

    <?php endwhile;
    wp_reset_query();
    wp_reset_postdata();
endif;
    wp_die();
}

Localize the script

wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'query_vars' => json_encode( $wp_query->query ),
    ));

NOTE- I know that I havent used the query_vars in the localize_script but I am too confused right now. And that pagination probably is not the best naming for what I want( it was from a tutorial website).

UPDATE 14:40 04/06/2019 = I have found some kind of way to return the ID with $post_id = isset( $_POST['post_id'] ) ? $_POST['post_id'] : 'N/A'; and giving the AJAX data post_id: post_id. But the problem now is that it gives me an array array(1) { ["postId"]=> string(2) "22" }.

UPDATE 15:37 04/06/2019 = It worked I have only left the number, $post_id = isset($_POST['post_id']) ? $_POST['post_id'] : 'N/A'; echo $post_id["postId"];

UPDATE 16:01 04/06/2019 I have finally done it, apparently it was just 2 lines of code and I have spent just under a week on this. It was a journey that has learned me a lot. Thanks for the help people. If anyone needs the code I'll update this.

Share Improve this question edited Jun 4, 2019 at 14:04 Kutuk asked Jun 3, 2019 at 17:25 KutukKutuk 33 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

What you're looking to accomplish isn't really pagination. That threw me off initially. You're building a navigation that will be site-wide.

If that's the case, you can either capture the ID from the url (this is not very performant) or add the ID to the markup.

This example shows you how to add the ID as a data attribute on the menu's anchor tag:

function my_nav_menu_link_attributes( $atts, $item, $args ) {
        // Replace with the theme location name for your menu.
    if ( 'menu-1' === $args->theme_location ) {
        // This works for posts or pages. Add extra custom post types to include.
        if ( isset( $item->object_id ) && ( 'post' === $item->object || 'page' === $item->object ) ) {
            $atts['data-post-id'] = $item->object_id;
        }
    }
    return $atts;
}
add_filter( 'nav_menu_link_attributes', 'my_nav_menu_link_attributes', 10, 3 );

If you use this, you can grab the data attribute data-post-id for each link that's clicked.

The markup will look something like this:

<li id="menu-item-52" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-52"><a href="/sample-page/" data-post-id="2">Sample Page</a></li>

本文标签: wp queryFinding post ID dynamically on click