This is the base of my code. The idea is that when I click submit the form posts to the same page and runs my code inside the if statement. The problem is that when I hit submit I get a Wordpress error saying Cannot load tb-export. I have done a lot of Google searches and can not find a solution.
Edit: Here is the whole class. https://pastebin.com/i03m9a3x
Edit Again: I took the code outside of the class and simplified it and I am still getting the error. Below is the simplified code and after I submit the form I get the error Cannot load export_display.
add_action('admin_menu', 'tb_admin_menu');
function tb_admin_menu() {
add_menu_page(
'Table Builder',
'Table Builder',
'read',
'i15-table-builder',
'',
'dashicons-screenoptions',
21
);
add_submenu_page('i15-table-builder', 'Export', 'Export', 'manage_options', 'export_display', 'export_display');
}
function export_display(){
if ($_POST['submit']) {
$post_args = array(
'post_type' => $_POST['post_type'],
'post__in' => $_POST['ids']
);
$posts = get_posts($post_args);
$count = 0;
foreach ( $rtp_posts as $post ) {
$write_array[$count] = array(
'post_id' => $post->ID,
'comment_status' => $post->comment_status,
'ping_status' => $post->ping_status,
'post_author' => $post->post_author,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_name' => $post->post_name,
'post_parent' => $post->post_parent,
'post_password' => $post->post_password,
'post_status' => $post->post_status,
'post_title' => $post->post_title,
'post_type' => $post->post_type,
'to_ping' => $post->to_ping,
'menu_order' => $post->menu_order
);
$taxonomies = get_object_taxonomies($post->post_type); // returns array of taxonomy names for post type, ex array("category", "post_tag");
foreach ($taxonomies as $taxonomy) {
$post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
$write_array[$count]['taxonomies'][$taxonomy] = $post_terms;
}
$post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id");
if (count($post_meta_infos)!=0) {
$sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
$countmetas = 0;
foreach ($post_meta_infos as $meta_info) {
$meta_key = $meta_info->meta_key;
if( $meta_key == '_wp_old_slug' ) continue;
$meta_value = addslashes($meta_info->meta_value);
$write_array[$count]['metas'][$countmetas]['meta_key'] = $meta_key;
$write_array[$count]['metas'][$countmetas]['meta_value'] = $meta_value;
$countmetas++;
}
}
$count++;
}
$write_array_encode = json_encode($write_array);
header('Content-disposition: attachment; filename=Table_Builder_Exported_Data.json');
header('Content-type: application/json');
echo $write_array_encode;
exit();
} else {
$template_args = array(
'post_type' => 'tb_template',
'post_status' => 'any',
'numberposts' => '-1'
);
$template_posts = get_posts($template_args);
foreach ( $template_posts as $template_post ) {
$select_templates .= '<option value="'.$template_post->ID.'">'.$template_post->post_title.'</option>';
}
echo '<form method="post" action="" enctype="multipart/form-data">';
echo '<input type="hidden" name="post_type" value="tb_template" />';
echo '<select multiple="multiple" name="ids[]" size="10">'.$select_templates.'</select>';
submit_button('Export Table Builder Templates');
echo '</form>';
echo "<hr />";
$table_args = array(
'post_type' => 'tb_table',
'post_status' => 'any',
'numberposts' => '-1'
);
$table_posts = get_posts($table_args);
foreach ( $table_posts as $table_post ) {
$select_tables .= '<option value="'.$table_post->ID.'">'.$table_post->post_title.'</option>';
}
echo '<form method="post" action="" enctype="multipart/form-data">';
echo '<input type="hidden" name="post_type" value="tb_table" />';
echo '<select multiple="multiple" name="ids[]" size="10">'.$select_tables.'</select>';
submit_button('Export Table Builder Tables');
echo '</form>';
}
}
The problem was inside my form. Previously the name of the hidden input was post_type. I guess this messed with some stuff because after I got rid of the underscore, it worked.
echo '<input type="hidden" name="posttype" value="tb_template" />';
Related
I'm using AJAX to filter posts by category, which is working fine. But when I try to add another filter to filter by a custom field called album date my original category filter doesn't work. Each filter on there own works but they don't work together. Here is the stripped down code.
I'm still learning how this all works together so any help would be greatly appreciated!
PHP CODE
function my_filter_function(){
// post date
$args = array(
'orderby' => 'date',
'order' => $_POST['date']
);
// for taxonomies / categories
if(isset($_POST['categoryfilter']))
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
)
);
// album year
if(isset($_POST['yearfilter']))
$args = array(
'meta_key' => 'album_year',
'meta_value' => $_POST['yearfilter'],
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h1>' . $query->post->post_title . '</h1>';
...
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
add_action('wp_ajax_myfilter', 'my_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'my_filter_function');
FORM CODE
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<?php
// Category Filter
if($terms = get_terms(array('taxonomy' => 'category', 'orderby' => 'name'))) :
echo '<select name="categoryfilter"><option value="">Select category...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<?php
// Year Filter
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'post',
'meta_key' => 'album_year',
'orderby' => 'meta_value',
'order' => 'DESC'
));
if( $posts ):
echo '<select name="yearfilter"><option value="">Select Year...</option>';
foreach($posts as $post):
$album_year = get_field('album_year');
echo '<option value="' . $album_year . '">' . $album_year . '</option>';
endforeach;
echo '</select>';
wp_reset_postdata();
endif;
?>
<label>
<input type="radio" name="date" value="ASC" /> Date: Ascending
</label>
<label>
<input type="radio" name="date" value="DESC" checked="checked" /> Date: Descending
</label>
<button>Apply filter</button>
<input type="hidden" name="action" value="myfilter">
</form>
I haven't tested this code but it looks like you are overriding your args variable for yearfilter.
This
// album year
if(isset($_POST['yearfilter'])) {
$args = array(
'meta_key' => 'album_year',
'meta_value' => $_POST['yearfilter'],
);
}
should be this
// album year
if(isset($_POST['yearfilter'])) {
$args['meta_key'] = 'album_year';
$args['meta_value'] = $_POST['yearfilter'];
}
If they are working individually this should fix things.
How to check if the post exists before wp_insert_post to avoid duplication?
The code below works if I remove the 'if' statement (post_exists()) and just keep reinserting posts producing multiple duplications. I wrote the if-statement with post_exists() just to start implementing the logic of checking but the moment I add the if statement, something breaks and the list below doesn't even get printed.
$body = wp_remote_retrieve_body( $request );
$data = json_decode(utf8ize($body), true);
$data_events = $data['events'];
if( ! empty( $data_events ) ) {
echo '<ul>';
foreach( $data_events as $event ) {
// the if statement below seems to break things ie. no li below printed.
if ( post_exists( $event['name'] ) == 0 ) {
echo 'exists';
} else {
echo 'doesnt exist';
}
echo '<li>';
echo $event['id'];
echo '' . $event['name'] . '';
echo '</li>';
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'description',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'post',
'post_category' => array(1),
'meta_input' => array(
'hq_id' => $event['id'],
)
);
//wp_insert_post($new_post); // commented out while testing the if statement.
}
echo '</ul>';
}
?>
Edit: please see the $data_events array:
https://pastebin.com/rC60iNyJ
The post_exists() function is not normally available on the front end. Instead of including another file you can use get_page_by_title to find a post by it's title. Just test for a null value to check if it doesn't exist.
Replace
if ( post_exists( $event['name'] ) == 0 ) {
with
if ( get_page_by_title( $event['name'] ) == null ) {
Try this code. you need to include this file.
because post_exists function will work on admin page not in frontend.
if ( ! is_admin() ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode(utf8ize($body), true);
$data_events = $data['events'];
if( ! empty( $data_events ) ) {
echo '<ul>';
foreach( $data_events as $event ) {
// the if statement below seems to break things ie. no li below printed.
if ( post_exists( $event['name'] ) == 0 ) {
echo 'doesnt exist';
} else {
echo 'exists';
}
echo '<li>';
echo $event['id'];
echo '' . $event['name'] . '';
echo '</li>';
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'description',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'post',
'post_category' => array(1),
'meta_input' => array(
'hq_id' => $event['id'],
)
);
//wp_insert_post($new_post); // commented out while testing the if statement.
}
echo '</ul>';
}
I'm using this code...
function include_post_types() {
$post_types = get_post_types( array (
'show_ui' => true
),
'objects' );
$return = '';
foreach ( $post_types as $post_type ) {
$my_sitemap_options = get_option( 'my_sitemap_settings' );
$post_type_name = $post_type->name;
if ($my_sitemap_options['post_types'] && in_array($post_type_name, $my_sitemap_options['post_types'])) {
$the_excluded = $post_type_name;
$return .= "'" . $the_excluded . "', ";
}
}
return $return;
}
... to return a list of custom post types that I have selected from an options page. This works fine, and if I do this...
echo included_post_types();
...I see this...
'clothes', 'shoes', 'jackets',
...which is what I excpected.
But the problem is when I try to use included_post_types() in a loop to only show posts with those post types, like this:
$sitemap_post_args = array(
'post_type' => array(included_post_types()),
'posts_per_page' => -1,
'orderby' =>'post_type',
'order' =>'asc'
);
$loop = new WP_Query($sitemap_post_args);
global $post_type;
global $post;
echo '<ul>';
$last_post_type = '';
while($loop->have_posts()): $loop->the_post();
$current_post_type = $post->post_type;
$current_post_type_object = get_post_type_object( $current_post_type );
if($current_post_type != $last_post_type) echo "<br /><li><strong>" . $current_post_type_object->labels->name . "</strong></li>";?>
<li><?php echo get_the_title(); ?></li>
<?php echo "\n";
$last_post_type = $current_post_type;
endwhile;
wp_reset_query();
echo '</ul>';
It simply doesn't display anything on my page, but it doesn't throw an error either.
I'm almost certain the problem is this line:
'post_type' => array(included_post_types()),
I even tried it like this...
'post_type' => included_post_types(),
...but it did not work.
If I try this...
'post_type' => array('clothes', 'shoes', 'jackets', ),
...it works, but I need to be able to use the function name.
Any suggestions would be helpful.
please replace below code with yours. It should be help.
function include_post_types() {
$post_types = get_post_types( array (
'show_ui' => true
),
'objects' );
$return = array();
foreach ( $post_types as $post_type ) {
$my_sitemap_options = get_option( 'my_sitemap_settings' );
$post_type_name = $post_type->name;
if ($my_sitemap_options['post_types'] && in_array($post_type_name, $my_sitemap_options['post_types'])) {
$the_excluded = $post_type_name;
$return[] = $the_excluded;
}
}
return $return;
}
and also replace below code that show posts
$post_type_list = include_post_types();
$sitemap_post_args = array(
'post_type' => $post_type_list,
'posts_per_page' => -1,
'orderby' =>'post_type',
'order' =>'asc'
);
i want to display product by category with dropdown
and i made this code but why the value not going inside the ?
function rakitpc() {
$args = array(
'posts_per_page' => -1,
'product_cat' => 'Tshirts',
'hide_empty' => 0,
'post_status' => 'publish',
'post_type' => 'product',
'orderby' => 'title',
'echo' => '0'
);
$products = new WP_Query( $args );
$output = '<select>';
// foreach ( $products as $product ) {
while ( $products->have_posts() ) {
$products->the_post();
$aa = the_permalink($post);
echo $aa;
$bb = the_title($post);
$output .= "<option value=\"<?php the_permalink(); ?>\"> <?php the_permalink(); ?></option>";
}
wp_reset_query();
$output .='</select>';
return $output;
}
add_shortcode( 'gege', 'rakitpc' );
This is the output That I get:
My reference: How do I display a "category products drop down in a wordpress page" in Woocommerce 2.5.2
Try the following that will give you a dropdown with the permalinks as <option> values displaying the product names (see the screenshot at the end).
You will need to set your category name (or categories names) in the array inside the funtion.
function rakitpc() {
// HERE below, define your Product category names
$term_names = array('T-shirts');
// The WP_Query
$query = new WP_Query( array(
'posts_per_page' => -1,
'post_type' => 'product',
'post_status' => 'publish',
'hide_empty' => 0,
'orderby' => 'title',
'tax_query' => array( array(
'taxonomy' => 'product_cat', // for a Product category (or 'product_tag' for a Product tag)
'field' => 'name', // can be 'name', 'slug' or 'term_id'
'terms' => $term_names,
) ),
'echo' => '0'
) );
$output = '<select>';
// foreach ( $products as $product ) {
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
$permalink = get_permalink($query->post->ID);
$title = $query->post->post_title;
$output .= '<option value="' . $permalink . '">' . $title . '</option>';
endwhile;
wp_reset_postdata();
$output .='</select>';
else :
$output = '<p>No products found<p>';
endif;
return $output;
}
add_shortcode( 'gege', 'rakitpc' );
Code goes in function.php file of your active child theme (or active theme). Tested and works.
I am fairly new to Wordpress and I am trying to make a function that loads images under a media category. The media category has a slug that I want to pass into the function. If there is an easier way to do this please let me know. Below is my code so far:
Functions.php
function get_image_by_slug($slug) {
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'attachment_category',
'field' => 'slug',
'terms' => $slug,
),
),
);
$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= $image->guid;
}
return $images;
}
function display_image_by_slug() {
$imgs = get_image_by_slug($slug);
$html = '<ul class="list-inline">';
foreach($imgs as $img) {
$html .= '<li><img src="' . $img . '" alt="" /></li>';
}
$html .= '</ul>';
return $html;
}
add_filter('display_slugs','display_image_by_slug');
In page
<?php apply_filter('display slugs', 'test_slug');?>
An attachment of image or file is just a post with the post_status = inherit and the post_type = attachment and it is saved into the wp_post & wp_postmeta , so can be queried with WP_Query or get_posts.
Note: The slug (post_name) is unique per post type.
You have to pass your slug in the query by replacing YOUR-SLUG in this place. &name=YOUR-SLUG
$_head = get_posts('post_type=attachment&name=YOUR-SLUG&posts_per_page=1&post_status=inherit');
$header = $_head ? array_pop($_head) : null;
$header_url = $header ? wp_get_attachment_url($header->ID) : '';
Another Method you can build your own custom function with the help that i have provided below.
function get_attachment_url_by_slug( $slug ) {
$args = array(
'post_type' => 'attachment',
'name' => sanitize_title($slug),
'posts_per_page' => 1,
'post_status' => 'inherit',
);
$_head = get_posts( $args );
$header = $_head ? array_pop($_head) : null;
return $header ? wp_get_attachment_url($header->ID) : '';
and then you can call using this function.
$header_url = get_attachment_url_by_slug('YOUR-SLUG');
So after looking around the Wordpress docs and understanding Naresh's answer I was able to come up with my own answer. Here it is...
$id = 'YOUR SLUG';
$args = array(
'post_type' => 'attachment',
'post_status' => 'any',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'media_category', // your taxonomy
'field' => 'slug',
'terms' => $id // term id (id of the media category)
)
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>'. wp_get_attachment_image( get_the_ID() );
if(empty_content(get_the_content())){
echo '<p>' . get_the_excerpt() . '</p></li>';
} else {
echo '<p>'.get_the_excerpt().'</p></li>';
}
}
} else {
// no attachments found
}
wp_reset_postdata();