qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
242,302 | <p>I want to make post titles mandatory in the post editor without Javascript or PHP validation, I'd like something really simple like adding the HTML "required" attribute to the post title input element.</p>
<p>I see there is "edit_form_top" and "edit_form_after_title" but those hook juste before and just after the title input.</p>
<p>Is there any way to actually change the HTML of the post title field ?</p>
| [
{
"answer_id": 242345,
"author": "brianjohnhanna",
"author_id": 65403,
"author_profile": "https://wordpress.stackexchange.com/users/65403",
"pm_score": 2,
"selected": false,
"text": "<p>There is <a href=\"https://core.trac.wordpress.org/browser/tags/4.6/src/wp-admin/edit-form-advanced.ph... | 2016/10/11 | [
"https://wordpress.stackexchange.com/questions/242302",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1381/"
] | I want to make post titles mandatory in the post editor without Javascript or PHP validation, I'd like something really simple like adding the HTML "required" attribute to the post title input element.
I see there is "edit\_form\_top" and "edit\_form\_after\_title" but those hook juste before and just after the title input.
Is there any way to actually change the HTML of the post title field ? | There is [no hook](https://core.trac.wordpress.org/browser/tags/4.6/src/wp-admin/edit-form-advanced.php#L541) to change the HTML of the input (only the `enter_title_here` filter to change the placeholder text). You could pull this off easily with jQuery, though. Try this in your functionality plugin or theme's `functions.php` file:
```
// Add to the new post screen for any post type
add_action( 'admin_footer-post-new.php', 'wpse_add_required_attr_to_title_field' );
// Add to the post edit screen for any post type
add_action( 'admin_footer-post.php', 'wpse_add_required_attr_to_title_field' );
function wpse_add_required_attr_to_title_field() {
?>
<script>
jQuery(document).ready(function($){
$('input[name=post_title]').prop('required',true);
});
</script>
<?php
}
```
I should note, however, not knowing what your user base for this site's administration looks like, that the prevention of submitting a form based solely on the required attribute [isn't implemented exactly the same across the board](http://caniuse.com/#feat=form-validation), so if this matters for your use case, you might want to look at an implementation that forces it's own alert, like for example in the [Force Post Title](https://wordpress.org/plugins/force-post-title/) plugin. |
242,331 | <p>I hope the title makes sense. I currently want to hide the default WYSIWYG editor on some of the pages but display it on others. </p>
<p>Is there a filter or a hook for the functions file? </p>
| [
{
"answer_id": 242342,
"author": "Patrick S",
"author_id": 30753,
"author_profile": "https://wordpress.stackexchange.com/users/30753",
"pm_score": 0,
"selected": false,
"text": "<pre><code>remove_post_type_support( 'page', 'editor' );\n</code></pre>\n\n<p>You can use it in several ways, ... | 2016/10/11 | [
"https://wordpress.stackexchange.com/questions/242331",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101285/"
] | I hope the title makes sense. I currently want to hide the default WYSIWYG editor on some of the pages but display it on others.
Is there a filter or a hook for the functions file? | I hope I understood your question right.
The following code will remove the editor from the pages using particular templates:
```
<?php
function wpse242371_remove_editor_from_some_pages()
{
global $post;
if( ! is_a($post, 'WP_Post') ) {
return;
}
/* basename is used for templates that are in the subdirectory of the theme */
$current_page_template_slug = basename( get_page_template_slug($post_id) );
/* file names of templates to remove the editor on */
$excluded_template_slugs = array(
'tmp_file_one.php',
'tmp_file_two.php',
'tmp_file_three.php'
);
if( in_array($current_page_template_slug, $excluded_template_slugs) ) {
/* remove editor from pages */
remove_post_type_support('page', 'editor');
/* if needed, add posts or CPTs to remove the editor on */
// remove_post_type_support('post', 'editor');
// remove_post_type_support('movies', 'editor');
}
}
add_action('admin_enqueue_scripts', 'wpse242371_remove_editor_from_some_pages');
``` |
242,360 | <p>I am developing a WordPress theme and there I used a custom post type <code>insurance_all</code> and a custom taxonomy <code>insurnce_all_categories</code> for the post type. But when I try to add a category the AJAX is not working but if I refresh the page the category is loaded. When I want to delete the category <code>An unidentified error has occurred</code> message show me on the top.</p>
<p>My custom post type is</p>
<pre><code><?php
$insurnce_all_labels = array(
'name' => _x( 'Insurance all ', 'Post Type General Name', 'safest' ),
'singular_name' => _x( 'Insurance all ', 'Post Type Singular Name', 'safest' ),
'menu_name' => __( 'Insurance all', 'safest' ),
'name_admin_bar' => __( 'Insurance all', 'safest' ),
'archives' => __( 'Insurance all Archives', 'safest' ),
'parent_item_colon' => __( 'Insurance all parent item:', 'safest' ),
'all_items' => __( 'Insurance all' , 'safest' ),
'add_new_item' => __( 'Add new item', 'safest' ),
'add_new' => __( 'Add new', 'safest' ),
'new_item' => __( 'Add new item', 'safest' ),
'edit_item' => __( 'Edit item', 'safest' ),
'update_item' => __( 'Update item', 'safest' ),
'view_item' => __( 'View item', 'safest' ),
'search_items' => __( 'Search item', 'safest' ),
'not_found' => __( 'Not found', 'safest' ),
'not_found_in_trash' => __( 'Not found in trash', 'safest' ),
'insert_into_item' => __( 'Insert into item', 'safest' ),
'uploaded_to_this_item' => __( 'Uploaded this item to Insurance all section', 'safest' ),
'items_list' => __( 'Insurance all', 'safest' ),
'items_list_navigation' => __( 'Insurance all section list navigation', 'safest' ),
'filter_items_list' => __( 'Filter Insurance all section list ', 'safest' ),
);
$insurnce_all_args = array(
'label' => __( 'Insurance all', 'safest' ),
'description' => __( 'Safest Insurance Insurance all for insurance menu', 'safest' ),
'labels' => $insurnce_all_labels,
'supports' => array('title','page-attributes','thumbnail','categories',),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'menu_position' => 8,
'menu_icon' => 'dashicons-menu',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type('insurance_all', $insurnce_all_args);
</code></pre>
<p>My custom taxonomy is</p>
<pre><code><?php
function insurance_all_category() {
$labels = array(
'name' => _x( 'Insurance all category', 'taxonomy general name' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Category' ),
'all_items' => __( 'All Categories' ),
'parent_item' => __( 'Parent Category' ),
'parent_item_colon' => __( 'Parent Category:' ),
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category' ),
'menu_name' => __( 'Categories' ),
);
register_taxonomy('insurnce_all_categories', array('insurance_all'),$args);
}
add_action('init','insurance_all_category');
</code></pre>
| [
{
"answer_id": 242365,
"author": "stims",
"author_id": 104727,
"author_profile": "https://wordpress.stackexchange.com/users/104727",
"pm_score": 0,
"selected": false,
"text": "<p>Your taxonomy registration in your example is showing this:</p>\n\n<pre><code>function insurance_all_category... | 2016/10/12 | [
"https://wordpress.stackexchange.com/questions/242360",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84311/"
] | I am developing a WordPress theme and there I used a custom post type `insurance_all` and a custom taxonomy `insurnce_all_categories` for the post type. But when I try to add a category the AJAX is not working but if I refresh the page the category is loaded. When I want to delete the category `An unidentified error has occurred` message show me on the top.
My custom post type is
```
<?php
$insurnce_all_labels = array(
'name' => _x( 'Insurance all ', 'Post Type General Name', 'safest' ),
'singular_name' => _x( 'Insurance all ', 'Post Type Singular Name', 'safest' ),
'menu_name' => __( 'Insurance all', 'safest' ),
'name_admin_bar' => __( 'Insurance all', 'safest' ),
'archives' => __( 'Insurance all Archives', 'safest' ),
'parent_item_colon' => __( 'Insurance all parent item:', 'safest' ),
'all_items' => __( 'Insurance all' , 'safest' ),
'add_new_item' => __( 'Add new item', 'safest' ),
'add_new' => __( 'Add new', 'safest' ),
'new_item' => __( 'Add new item', 'safest' ),
'edit_item' => __( 'Edit item', 'safest' ),
'update_item' => __( 'Update item', 'safest' ),
'view_item' => __( 'View item', 'safest' ),
'search_items' => __( 'Search item', 'safest' ),
'not_found' => __( 'Not found', 'safest' ),
'not_found_in_trash' => __( 'Not found in trash', 'safest' ),
'insert_into_item' => __( 'Insert into item', 'safest' ),
'uploaded_to_this_item' => __( 'Uploaded this item to Insurance all section', 'safest' ),
'items_list' => __( 'Insurance all', 'safest' ),
'items_list_navigation' => __( 'Insurance all section list navigation', 'safest' ),
'filter_items_list' => __( 'Filter Insurance all section list ', 'safest' ),
);
$insurnce_all_args = array(
'label' => __( 'Insurance all', 'safest' ),
'description' => __( 'Safest Insurance Insurance all for insurance menu', 'safest' ),
'labels' => $insurnce_all_labels,
'supports' => array('title','page-attributes','thumbnail','categories',),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'menu_position' => 8,
'menu_icon' => 'dashicons-menu',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type('insurance_all', $insurnce_all_args);
```
My custom taxonomy is
```
<?php
function insurance_all_category() {
$labels = array(
'name' => _x( 'Insurance all category', 'taxonomy general name' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Category' ),
'all_items' => __( 'All Categories' ),
'parent_item' => __( 'Parent Category' ),
'parent_item_colon' => __( 'Parent Category:' ),
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category' ),
'menu_name' => __( 'Categories' ),
);
register_taxonomy('insurnce_all_categories', array('insurance_all'),$args);
}
add_action('init','insurance_all_category');
``` | Your taxonomy registration in your example is showing this:
```
function insurance_all_category(){
$labels = array(
'name' =>_x( 'Insurance all category', 'taxonomy general name' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Category' ),
'all_items' => __( 'All Categories' ),
'parent_item' => __( 'Parent Category' ),
'parent_item_colon' => __( 'Parent Category:' ),
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category' ),
'menu_name' => __( 'Categories' ),
);
register_taxonomy('insurnce_all_categories', array('insurance_all'),$args);}add_action('init','insurance_all_category');?>
```
and needs to be this:
```
function insurance_all_category(){
$labels = array(
'name' =>_x( 'Insurance all category', 'taxonomy general name' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Category' ),
'all_items' => __( 'All Categories' ),
'parent_item' => __( 'Parent Category' ),
'parent_item_colon' => __( 'Parent Category:' ),
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category' ),
'menu_name' => __( 'Categories' ),
);
//new code
$args = array(
'labels' => $labels
);
register_taxonomy('insurnce_all_categories', array('insurance_all'),$args);}add_action('init','insurance_all_category');?>
``` |
242,391 | <p>I've about 12 records and that means I should have 4 pages. My best attempt so far at getting pagination to work is this, and I'd really appreciate if someone could tell me where exactly am I going wrong?</p>
<pre><code> <div id="main-content">
<div class="container">
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'job',
'posts_per_page' => 3,
'paged' => $paged
);
$query = new WP_Query( $args );
while ( $query->have_posts()): $query->the_post();
<h1> <?php the_title(); ?> </h1>
<p> <?php the_excerpt(); ?> </p>
<?php
endwhile; ?>
</div> <!-- .container -->
</div> <!-- #main-content -->
<!-- Start Navigation Here -->
<?php
global $wp_query;
$total_pages = $wp_query->max_num_pages;
if ($total_pages > 1) {
$current_page = max( 1, get_query_var('paged'));
echo '<div class="page_nav">';
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'current' => $current_page,
'total' => $total_pages,
'prev_text' => 'Prev',
'next_text' => 'Next'
));
echo '</div>';
}
?>
<?php wp_reset_postdata(); ?>
</code></pre>
<h2> </h2>
<p>UPDATED CODE: </p>
<p>Okay this is much simplified, but this continues to show 5 pages irrespective of how many 'posts_per_page' count I set. With total of 24 records, I am expecting only 2 pages (aka max_num_pages), but I keep getting '5'. Here's my simplified, latest code:
<pre><code> //Generate the loop here
//Prepare arguments for WP_QUERY
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 12,
'post_type' => 'job',
'paged' => $paged
);
$query = new WP_Query( $args );
if ($query->have_posts()) {
while ( $query->have_posts()) {
$query->the_post();
?> <li><?php the_title(); ?></li> <?php
}
} else {
echo "<h2>No Jobs Found</h2>";
}
// Pagination begins here
$paginateArgs = array(
'base' => '%_%',
'format' => '?paged=%#%',
'current' => $paged
);
echo paginate_links( $paginateArgs );
wp_reset_postdata();
?>
</code></pre>
| [
{
"answer_id": 242373,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 4,
"selected": true,
"text": "<p>The alternative to <a href=\"https://developer.wordpress.org/reference/hooks/wp_head/\" rel=\"noreferrer\"><co... | 2016/10/12 | [
"https://wordpress.stackexchange.com/questions/242391",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21100/"
] | I've about 12 records and that means I should have 4 pages. My best attempt so far at getting pagination to work is this, and I'd really appreciate if someone could tell me where exactly am I going wrong?
```
<div id="main-content">
<div class="container">
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'job',
'posts_per_page' => 3,
'paged' => $paged
);
$query = new WP_Query( $args );
while ( $query->have_posts()): $query->the_post();
<h1> <?php the_title(); ?> </h1>
<p> <?php the_excerpt(); ?> </p>
<?php
endwhile; ?>
</div> <!-- .container -->
</div> <!-- #main-content -->
<!-- Start Navigation Here -->
<?php
global $wp_query;
$total_pages = $wp_query->max_num_pages;
if ($total_pages > 1) {
$current_page = max( 1, get_query_var('paged'));
echo '<div class="page_nav">';
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'current' => $current_page,
'total' => $total_pages,
'prev_text' => 'Prev',
'next_text' => 'Next'
));
echo '</div>';
}
?>
<?php wp_reset_postdata(); ?>
```
UPDATED CODE:
Okay this is much simplified, but this continues to show 5 pages irrespective of how many 'posts\_per\_page' count I set. With total of 24 records, I am expecting only 2 pages (aka max\_num\_pages), but I keep getting '5'. Here's my simplified, latest code:
```
//Generate the loop here
//Prepare arguments for WP_QUERY
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 12,
'post_type' => 'job',
'paged' => $paged
);
$query = new WP_Query( $args );
if ($query->have_posts()) {
while ( $query->have_posts()) {
$query->the_post();
?> <li><?php the_title(); ?></li> <?php
}
} else {
echo "<h2>No Jobs Found</h2>";
}
// Pagination begins here
$paginateArgs = array(
'base' => '%_%',
'format' => '?paged=%#%',
'current' => $paged
);
echo paginate_links( $paginateArgs );
wp_reset_postdata();
?>
``` | The alternative to [`wp_head`](https://developer.wordpress.org/reference/hooks/wp_head/) action in admin area is [`admin_head`](https://developer.wordpress.org/reference/hooks/admin_head/). But, if your CSS depends on another stylesheet, you should use [`wp_add_inline_style()`](https://codex.wordpress.org/Function_Reference/wp_add_inline_style) function hooked to [`admin_enqueue_scripts` action](https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/). |
242,423 | <p>I have a strange request I thought would be simple. I need to break the Wordpress pagination. Specifically, I need to make the <code>/page/2/</code>, <code>/page/3/</code>, and so on, links disabled.</p>
<p>I tried:</p>
<pre><code>RewriteRule ^page/[0-9] http://www.mysite[dot]com/404.php [R]
</code></pre>
<p>But that is a no go...
Anyone?</p>
<p>Thanks</p>
| [
{
"answer_id": 242429,
"author": "Nick Barth",
"author_id": 101651,
"author_profile": "https://wordpress.stackexchange.com/users/101651",
"pm_score": 0,
"selected": false,
"text": "<p>That rule looks OK; the problem might be where you put it. Order matters in .htaccess, so be sure you're... | 2016/10/12 | [
"https://wordpress.stackexchange.com/questions/242423",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88384/"
] | I have a strange request I thought would be simple. I need to break the Wordpress pagination. Specifically, I need to make the `/page/2/`, `/page/3/`, and so on, links disabled.
I tried:
```
RewriteRule ^page/[0-9] http://www.mysite[dot]com/404.php [R]
```
But that is a no go...
Anyone?
Thanks | Thanks Nick! I thought that would work, and I placed it right after "RewriteEngine On" so it came first.
I did find a working solution for handling it though (after 2 hrs):
```
RewriteRule ^page/(.*)$ /$1 [G]
```
In case anyone else needs to do the same ... |
242,428 | <p>I am new to wp dev and trying to figure out how to replace or change the query woocommerce makes that shows all my products on any archive page, or page that shows my list of products, not sure what it is called but the page that shows the pic, name, price & link to product page. I have multiple categories so i guess i would need to add the code to show the different categories depending on which cat page they are on? Unless i am looking it to this too deeply. </p>
<p>I am trying to make an advanced loop that shows me groups of products based on a few things. First i want to see all the featured products, then i want to see the products that are not older than 6 months old, then everything else in menu order then title order ascending. </p>
<p>To make it even more complicated i don't want any duplicates. I think my code is working but I am not sure exactly where or how to place it so woo takes off with it and shows my results. Below is the code i am using, I am placing it in the woocommerce.php page in my child theme and it doesn't show me anything unless i echo or print_r something. So I know I am missing something but being new I don't know what I need to search for to include to see the results.</p>
<p>My code: (woocommerce.php)</p>
<pre><code><?php
if ( is_shop() || is_product_category() || is_product_tag() ) { // Only run on shop archive pages, not single products or other pages
// Products per page
$per_page = 12;
if ( get_query_var( 'taxonomy' ) ) { // If on a product taxonomy archive (category or tag)
//First loop
$args = array(
'post_type' => 'product',
'orderby' => array( 'meta_value' => 'DESC' ),
'meta_key' => '_featured',
'posts_per_page' => $per_page,
'paged' => get_query_var( 'paged' ),
);
$loop = new WP_Query( $args );
if (have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
$post_id = get_the_ID();
$do_not_duplicate[] = $post_id;
endwhile;
endif;
rewind_posts();
//Second loop
$args = array(
'post_type' => 'product',
'orderby' => 'date',
'order' => 'DESC',
'date_query' => array(
array(
'before' => '6 months ago',
),
),
'post__not_in' => $do_not_duplicate
);
$loop = new WP_Query( $args );
if (have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
$post_id = get_the_ID();
$do_not_duplicate[] = $post_id;
endwhile;
endif;
rewind_posts();
//Third loop
$args = array(
'post_type' => 'product',
'orderby' => array(
'menu_order' => 'ASC',
'title' => 'ASC',
'post__not_in' => $do_not_duplicate
),
);
$loop = new WP_Query( $args );
if (have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
$post_id = get_the_ID();
$do_not_duplicate[] = $post_id;
endwhile;
endif;
} else { // On main shop page
$args = array(
'post_type' => 'product',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => $per_page,
'paged' => get_query_var( 'paged' ),
);
}
// Set the query
$products = new WP_Query( $args );
// Standard loop
if ( $products->have_posts() ) :
while ( $products->have_posts() ) : $products->the_post();
endwhile;
wp_reset_postdata();
endif;
} else { // If not on archive page (cart, checkout, etc), do normal operations
woocommerce_content();
}
</code></pre>
<p>Any help to steer me in the right direction would be great help!</p>
<p><strong>Update</strong></p>
<p>I forgot to add <code>'post_type' => 'product'</code>in my args (updated it just now), but now that I can see my titles when I add <code>the_title();</code> in my while loop, how do I tell it instead to spit it all out like it would for any archive page(call a template?), also how do I make it more generic so depending on which category/archive page I am on it will just show products for that category? Thanks again!</p>
| [
{
"answer_id": 242429,
"author": "Nick Barth",
"author_id": 101651,
"author_profile": "https://wordpress.stackexchange.com/users/101651",
"pm_score": 0,
"selected": false,
"text": "<p>That rule looks OK; the problem might be where you put it. Order matters in .htaccess, so be sure you're... | 2016/10/12 | [
"https://wordpress.stackexchange.com/questions/242428",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104167/"
] | I am new to wp dev and trying to figure out how to replace or change the query woocommerce makes that shows all my products on any archive page, or page that shows my list of products, not sure what it is called but the page that shows the pic, name, price & link to product page. I have multiple categories so i guess i would need to add the code to show the different categories depending on which cat page they are on? Unless i am looking it to this too deeply.
I am trying to make an advanced loop that shows me groups of products based on a few things. First i want to see all the featured products, then i want to see the products that are not older than 6 months old, then everything else in menu order then title order ascending.
To make it even more complicated i don't want any duplicates. I think my code is working but I am not sure exactly where or how to place it so woo takes off with it and shows my results. Below is the code i am using, I am placing it in the woocommerce.php page in my child theme and it doesn't show me anything unless i echo or print\_r something. So I know I am missing something but being new I don't know what I need to search for to include to see the results.
My code: (woocommerce.php)
```
<?php
if ( is_shop() || is_product_category() || is_product_tag() ) { // Only run on shop archive pages, not single products or other pages
// Products per page
$per_page = 12;
if ( get_query_var( 'taxonomy' ) ) { // If on a product taxonomy archive (category or tag)
//First loop
$args = array(
'post_type' => 'product',
'orderby' => array( 'meta_value' => 'DESC' ),
'meta_key' => '_featured',
'posts_per_page' => $per_page,
'paged' => get_query_var( 'paged' ),
);
$loop = new WP_Query( $args );
if (have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
$post_id = get_the_ID();
$do_not_duplicate[] = $post_id;
endwhile;
endif;
rewind_posts();
//Second loop
$args = array(
'post_type' => 'product',
'orderby' => 'date',
'order' => 'DESC',
'date_query' => array(
array(
'before' => '6 months ago',
),
),
'post__not_in' => $do_not_duplicate
);
$loop = new WP_Query( $args );
if (have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
$post_id = get_the_ID();
$do_not_duplicate[] = $post_id;
endwhile;
endif;
rewind_posts();
//Third loop
$args = array(
'post_type' => 'product',
'orderby' => array(
'menu_order' => 'ASC',
'title' => 'ASC',
'post__not_in' => $do_not_duplicate
),
);
$loop = new WP_Query( $args );
if (have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
$post_id = get_the_ID();
$do_not_duplicate[] = $post_id;
endwhile;
endif;
} else { // On main shop page
$args = array(
'post_type' => 'product',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => $per_page,
'paged' => get_query_var( 'paged' ),
);
}
// Set the query
$products = new WP_Query( $args );
// Standard loop
if ( $products->have_posts() ) :
while ( $products->have_posts() ) : $products->the_post();
endwhile;
wp_reset_postdata();
endif;
} else { // If not on archive page (cart, checkout, etc), do normal operations
woocommerce_content();
}
```
Any help to steer me in the right direction would be great help!
**Update**
I forgot to add `'post_type' => 'product'`in my args (updated it just now), but now that I can see my titles when I add `the_title();` in my while loop, how do I tell it instead to spit it all out like it would for any archive page(call a template?), also how do I make it more generic so depending on which category/archive page I am on it will just show products for that category? Thanks again! | Thanks Nick! I thought that would work, and I placed it right after "RewriteEngine On" so it came first.
I did find a working solution for handling it though (after 2 hrs):
```
RewriteRule ^page/(.*)$ /$1 [G]
```
In case anyone else needs to do the same ... |
242,462 | <p>I have a custom meta field that I want to display as my excerpt. I use a filter that does this for me:</p>
<pre><code>add_filter( 'get_the_excerpt', function($output){
$output=get_post_meta(get_the_ID(), 'my_meta_field', true);
return $output;
});
</code></pre>
<p>Now whenever I use <code>get_the_excerpt()</code> or <code>the_excerpt()</code> inside of the loop I get the content of <code>my_meta_field</code>. </p>
<p>But since WP 4.5.0 <a href="https://developer.wordpress.org/reference/functions/get_the_excerpt/" rel="nofollow"><code>get_the_excerpt()</code></a> accepts a Post ID or WP_Post object as parameter. I would like to keep this functionality intact while using my filter. </p>
<p>So imagine I want to use <code>get_the_excerpt()</code> outside of the loop. When I call <code>get_the_excerpt(1234)</code> (1234 being the ID of a post) I get the wrong excerpt back because the <code>get_the_ID()</code> in my filter grabs whatever <code>global $post</code> has to offer at that moment. </p>
<p>What is the most elegant / efficient way to solve this? Can I somehow use the ID I am passing to get_the_excerpt inside my filter? Or do I need to create a mini loop and set <code>global $post</code> to <code>get_post(1234)</code>? </p>
| [
{
"answer_id": 242465,
"author": "Jonny Perl",
"author_id": 40765,
"author_profile": "https://wordpress.stackexchange.com/users/40765",
"pm_score": -1,
"selected": false,
"text": "<p>Even if you're not in the loop, if you're on within a post or page (or other post type) generated from Wo... | 2016/10/12 | [
"https://wordpress.stackexchange.com/questions/242462",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10595/"
] | I have a custom meta field that I want to display as my excerpt. I use a filter that does this for me:
```
add_filter( 'get_the_excerpt', function($output){
$output=get_post_meta(get_the_ID(), 'my_meta_field', true);
return $output;
});
```
Now whenever I use `get_the_excerpt()` or `the_excerpt()` inside of the loop I get the content of `my_meta_field`.
But since WP 4.5.0 [`get_the_excerpt()`](https://developer.wordpress.org/reference/functions/get_the_excerpt/) accepts a Post ID or WP\_Post object as parameter. I would like to keep this functionality intact while using my filter.
So imagine I want to use `get_the_excerpt()` outside of the loop. When I call `get_the_excerpt(1234)` (1234 being the ID of a post) I get the wrong excerpt back because the `get_the_ID()` in my filter grabs whatever `global $post` has to offer at that moment.
What is the most elegant / efficient way to solve this? Can I somehow use the ID I am passing to get\_the\_excerpt inside my filter? Or do I need to create a mini loop and set `global $post` to `get_post(1234)`? | In spite of what the Codex says, since WP 4.5, where the addition of the post argument to the function get\_the\_excerpt was added, this filter takes two arguments. The second argument is the post object whose excerpt you are manipulating.
So the function still works in the loop without an explicit post, we make the second argument optional.
```
add_filter( 'get_the_excerpt', 'wpse_242462_excerpt_filter' );
function wpse_242462_excerpt_filter( $excerpt, $post = null ){
if ( $post ) {
$ID = $post->ID;
} else {
$ID = get_the_ID();
}
$excerpt = get_post_meta( $ID, 'wpse_242462_meta_field', true);
return $excerpt;
});
```
Hopefully it goes without saying that you need to substitute whatever meta key you are already using. |
242,464 | <p>I am looking to add the option of adding an anchor to my page in the Menu's page.</p>
<p>By default, the link has the <code>Navigation Label</code> with the link to the page, a <code>Remove</code> and a <code>Cancel</code> link. However, I need to add a page with a named anchor. So far, I've added all my links with <code>Custom Links</code>, but I would prefer being able to add my page in case my <code>slug</code> changes.</p>
<p>Is this possible via <code>functions.php</code>, or perhaps a plugin?</p>
| [
{
"answer_id": 242470,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 3,
"selected": true,
"text": "<p>There's a specific filter for each nav item's attributes: <a href=\"https://codex.wordpress.org/Plugin_API/Fil... | 2016/10/12 | [
"https://wordpress.stackexchange.com/questions/242464",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89512/"
] | I am looking to add the option of adding an anchor to my page in the Menu's page.
By default, the link has the `Navigation Label` with the link to the page, a `Remove` and a `Cancel` link. However, I need to add a page with a named anchor. So far, I've added all my links with `Custom Links`, but I would prefer being able to add my page in case my `slug` changes.
Is this possible via `functions.php`, or perhaps a plugin? | There's a specific filter for each nav item's attributes: [nav\_menu\_link\_attributes](https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_link_attributes).
So, you can put in your functions.php file something like:
```
function mysite_add_anchor( $atts, $item, $args ) {
$atts['href'] .= ( !empty( $item->xfn ) ? '#' . $item->xfn : '' );
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'mysite_add_anchor', 10, 3 );
```
What this does, is check the Link Relationship (XFN), and if it's not empty, it will add that to the end of your link with the #.
A couple things, if you don't see "Link Relationship" in the menu item, check the "Screen Options" at the top and check the box. ALSO, you can use almost any of the other properties you aren't currently using for Advanced Menu Properties.
<https://codex.wordpress.org/Appearance_Menus_Screen>
Not sure if Link Relationship isn't the right one, but it's the one I use the least.
Note: I didn't test the code. |
242,473 | <p>I'm trying to create a portfolio with WordPress using a Custom Post Type to display my projects. Each project I want to display on my static front page with a featured image as a thumbnail, and by clicking on a thumbnail would take me directly to the project.</p>
<p>How do I post Custom Post Types to the static front page? I want to show only the latest 6 posts, and then I'd have a link to the rest via my navigation.</p>
| [
{
"answer_id": 242475,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Edit: This answer was written before I realised the OP has a static front page.</strong> ... | 2016/10/12 | [
"https://wordpress.stackexchange.com/questions/242473",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104792/"
] | I'm trying to create a portfolio with WordPress using a Custom Post Type to display my projects. Each project I want to display on my static front page with a featured image as a thumbnail, and by clicking on a thumbnail would take me directly to the project.
How do I post Custom Post Types to the static front page? I want to show only the latest 6 posts, and then I'd have a link to the rest via my navigation. | So if you've registered a CPT called `wpse_242473_custom_post_type` you can use this to put 6 recent posts of that type onto your static front page (or anywhere). You can use a shortcode or a template tag and the function should work for both.
It's a modification of some code I use in a lot of sites. Put it in your theme's `functions.php`. Modify the HTML I've used to suit yourself, of course.
I've added a twist that I've been meaning to try for a while, so if it chokes on you let me know and I'll test it properly. What I've added is a full set of optional arguments that let the same function work, I hope, for both a shortcode and a template tag. You can either put `[recentposts]` into the visual editor on any page, or you can put `<?php wpse_242473_recent_posts(); ?>` into any template of your theme.
To put it into the template for your static front page, edit (or create) the template `front-page.php`. This will be automatically selected for your static front page, without you having to select it within the page edit screen.
```
function wpse_242473_recent_posts( $atts = null, $content = null, $tag = null ) {
$out = '';
$args = array(
'numberposts' => '6',
'post_status' => 'publish',
'post_type' => 'wpse_242473_custom_post_type' ,
);
$recent = wp_get_recent_posts( $args );
if ( $recent ) {
$out .= '<section class="overview">';
$out .= '<h1>Recent Projects</h1>';
$out .= '<div class="overview">';
foreach ( $recent as $item ) {
$out .= '<a href="' . get_permalink( $item['ID'] ) . '">';
$out .= get_the_post_thumbnail( $item['ID'] );
$out .= '</a>';
}
$out .= '</div></section>';
}
if ( $tag ) {
return $out;
} else {
echo $out;
}
}
add_shortcode( 'recentposts', 'wpse_242473_recent_posts' );
```
It's a straightforward retrieval of the posts you want.
The `foreach` loop builds your HTML and then the conditional at the end either returns the HTML, if you've used a shortcode, or echoes it if your calling the function as a template tag.
What a lot of articles on the web don't show you is that third argument passed to all shortcode handlers. When you use the shortcode it contains the shortcode name, so a handler could in theory handle multiple shortcodes. In this case we're using it to tell whether the function was indeed called as a shortcode handler or not. |
242,493 | <p>I am trying to get all categories which are having products but getting also the categories which are having no products. </p>
<p>WordPress version 4.6.1</p>
<pre><code>wp_dropdown_categories(
array(
'class' => 'product-category-field',
'id' => 'product-category',
'name' => 'category',
'taxonomy' => 'product_cat',
'selected' => get_query_var('product_cat' ),
'hierarchical' => 1,
'hide_empty' => 1,
'value_field' => 'slug',
'show_count' => 1
)
);
</code></pre>
<p>Even <code>get_terms</code> is displaying empty categories with the below code.</p>
<pre><code><?php $terms = get_terms('product_cat', array( 'parent' => 0 ));
if( $terms ):
$original_query = $wp_query;
foreach ( $terms as $key => $term ):
?>
<li>
<?php echo $term->name; ?>
<ul>
<?php
$child_terms = get_terms(
'product_cat',
array(
'child_of' => $term->term_id,
'hide_empty' => true
)
);
foreach ( $child_terms as $child_term ) {
$re_child_terms = get_terms(
'product_cat',
array(
'child_of' => $child_term->term_id,
'hide_empty' => true
)
);
if ( ! $re_child_terms ){
?>
<li>
<?php echo $child_term->name; ?>
</li>
<?php
}
}
?>
</ul>
</li>
<?php
endforeach;
$wp_query = null;
$wp_query = $original_query;
?>
</ul>
<?php endif; ?>
</code></pre>
<blockquote>
<p>Note: In both case do not want to display categories having zero
products.</p>
</blockquote>
| [
{
"answer_id": 242475,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Edit: This answer was written before I realised the OP has a static front page.</strong> ... | 2016/10/13 | [
"https://wordpress.stackexchange.com/questions/242493",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81273/"
] | I am trying to get all categories which are having products but getting also the categories which are having no products.
WordPress version 4.6.1
```
wp_dropdown_categories(
array(
'class' => 'product-category-field',
'id' => 'product-category',
'name' => 'category',
'taxonomy' => 'product_cat',
'selected' => get_query_var('product_cat' ),
'hierarchical' => 1,
'hide_empty' => 1,
'value_field' => 'slug',
'show_count' => 1
)
);
```
Even `get_terms` is displaying empty categories with the below code.
```
<?php $terms = get_terms('product_cat', array( 'parent' => 0 ));
if( $terms ):
$original_query = $wp_query;
foreach ( $terms as $key => $term ):
?>
<li>
<?php echo $term->name; ?>
<ul>
<?php
$child_terms = get_terms(
'product_cat',
array(
'child_of' => $term->term_id,
'hide_empty' => true
)
);
foreach ( $child_terms as $child_term ) {
$re_child_terms = get_terms(
'product_cat',
array(
'child_of' => $child_term->term_id,
'hide_empty' => true
)
);
if ( ! $re_child_terms ){
?>
<li>
<?php echo $child_term->name; ?>
</li>
<?php
}
}
?>
</ul>
</li>
<?php
endforeach;
$wp_query = null;
$wp_query = $original_query;
?>
</ul>
<?php endif; ?>
```
>
> Note: In both case do not want to display categories having zero
> products.
>
>
> | So if you've registered a CPT called `wpse_242473_custom_post_type` you can use this to put 6 recent posts of that type onto your static front page (or anywhere). You can use a shortcode or a template tag and the function should work for both.
It's a modification of some code I use in a lot of sites. Put it in your theme's `functions.php`. Modify the HTML I've used to suit yourself, of course.
I've added a twist that I've been meaning to try for a while, so if it chokes on you let me know and I'll test it properly. What I've added is a full set of optional arguments that let the same function work, I hope, for both a shortcode and a template tag. You can either put `[recentposts]` into the visual editor on any page, or you can put `<?php wpse_242473_recent_posts(); ?>` into any template of your theme.
To put it into the template for your static front page, edit (or create) the template `front-page.php`. This will be automatically selected for your static front page, without you having to select it within the page edit screen.
```
function wpse_242473_recent_posts( $atts = null, $content = null, $tag = null ) {
$out = '';
$args = array(
'numberposts' => '6',
'post_status' => 'publish',
'post_type' => 'wpse_242473_custom_post_type' ,
);
$recent = wp_get_recent_posts( $args );
if ( $recent ) {
$out .= '<section class="overview">';
$out .= '<h1>Recent Projects</h1>';
$out .= '<div class="overview">';
foreach ( $recent as $item ) {
$out .= '<a href="' . get_permalink( $item['ID'] ) . '">';
$out .= get_the_post_thumbnail( $item['ID'] );
$out .= '</a>';
}
$out .= '</div></section>';
}
if ( $tag ) {
return $out;
} else {
echo $out;
}
}
add_shortcode( 'recentposts', 'wpse_242473_recent_posts' );
```
It's a straightforward retrieval of the posts you want.
The `foreach` loop builds your HTML and then the conditional at the end either returns the HTML, if you've used a shortcode, or echoes it if your calling the function as a template tag.
What a lot of articles on the web don't show you is that third argument passed to all shortcode handlers. When you use the shortcode it contains the shortcode name, so a handler could in theory handle multiple shortcodes. In this case we're using it to tell whether the function was indeed called as a shortcode handler or not. |
242,517 | <p>On my site I hava two forms witch send email. The one whit no attachment needed is sent correnctly, but the other ony witch has an attachment does not get sent. I am using SMTP config whit Postman SMTP plugin.</p>
<pre><code>move_uploaded_file($_FILES["cv"]["tmp_name"],WP_CONTENT_DIR .'/uploads/CV/'.basename($_FILES['cv']['name']));
move_uploaded_file($_FILES["lm"]["tmp_name"],WP_CONTENT_DIR .'/uploads/lm/'.basename($_FILES['lm']['name']));
$attachments = array(
WP_CONTENT_DIR ."/uploads/CV/".$_FILES["cv"]["name"],
WP_CONTENT_DIR ."/uploads/lm/".$_FILES["lm"]["name"]
);
</code></pre>
<p>this is the code I use for storeing and reaching the attachments and simpli useing the wp_mail function to send it like this:</p>
<pre><code>$sent=wp_mail($s, $subject, $message, $headers,$attachments);
</code></pre>
<p>On the other form I am useing the same code just whitout the $attachments variable.
The one whitout attachements get sent but the other one does not.
Can anyone help me finx my problem?</p>
| [
{
"answer_id": 242475,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Edit: This answer was written before I realised the OP has a static front page.</strong> ... | 2016/10/13 | [
"https://wordpress.stackexchange.com/questions/242517",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99365/"
] | On my site I hava two forms witch send email. The one whit no attachment needed is sent correnctly, but the other ony witch has an attachment does not get sent. I am using SMTP config whit Postman SMTP plugin.
```
move_uploaded_file($_FILES["cv"]["tmp_name"],WP_CONTENT_DIR .'/uploads/CV/'.basename($_FILES['cv']['name']));
move_uploaded_file($_FILES["lm"]["tmp_name"],WP_CONTENT_DIR .'/uploads/lm/'.basename($_FILES['lm']['name']));
$attachments = array(
WP_CONTENT_DIR ."/uploads/CV/".$_FILES["cv"]["name"],
WP_CONTENT_DIR ."/uploads/lm/".$_FILES["lm"]["name"]
);
```
this is the code I use for storeing and reaching the attachments and simpli useing the wp\_mail function to send it like this:
```
$sent=wp_mail($s, $subject, $message, $headers,$attachments);
```
On the other form I am useing the same code just whitout the $attachments variable.
The one whitout attachements get sent but the other one does not.
Can anyone help me finx my problem? | So if you've registered a CPT called `wpse_242473_custom_post_type` you can use this to put 6 recent posts of that type onto your static front page (or anywhere). You can use a shortcode or a template tag and the function should work for both.
It's a modification of some code I use in a lot of sites. Put it in your theme's `functions.php`. Modify the HTML I've used to suit yourself, of course.
I've added a twist that I've been meaning to try for a while, so if it chokes on you let me know and I'll test it properly. What I've added is a full set of optional arguments that let the same function work, I hope, for both a shortcode and a template tag. You can either put `[recentposts]` into the visual editor on any page, or you can put `<?php wpse_242473_recent_posts(); ?>` into any template of your theme.
To put it into the template for your static front page, edit (or create) the template `front-page.php`. This will be automatically selected for your static front page, without you having to select it within the page edit screen.
```
function wpse_242473_recent_posts( $atts = null, $content = null, $tag = null ) {
$out = '';
$args = array(
'numberposts' => '6',
'post_status' => 'publish',
'post_type' => 'wpse_242473_custom_post_type' ,
);
$recent = wp_get_recent_posts( $args );
if ( $recent ) {
$out .= '<section class="overview">';
$out .= '<h1>Recent Projects</h1>';
$out .= '<div class="overview">';
foreach ( $recent as $item ) {
$out .= '<a href="' . get_permalink( $item['ID'] ) . '">';
$out .= get_the_post_thumbnail( $item['ID'] );
$out .= '</a>';
}
$out .= '</div></section>';
}
if ( $tag ) {
return $out;
} else {
echo $out;
}
}
add_shortcode( 'recentposts', 'wpse_242473_recent_posts' );
```
It's a straightforward retrieval of the posts you want.
The `foreach` loop builds your HTML and then the conditional at the end either returns the HTML, if you've used a shortcode, or echoes it if your calling the function as a template tag.
What a lot of articles on the web don't show you is that third argument passed to all shortcode handlers. When you use the shortcode it contains the shortcode name, so a handler could in theory handle multiple shortcodes. In this case we're using it to tell whether the function was indeed called as a shortcode handler or not. |
242,536 | <p>I am currently trying to add a list of categories that a custom post is in (only have 3 categories). by using the code below, I have managed to output ALL categories into a list but what am I missing to filter just the categories that that post is in... Been stuck for days!</p>
<p>Here is the link to better explain - <a href="http://mgmtphdjobs.com/manage-jobs/" rel="nofollow">http://mgmtphdjobs.com/manage-jobs/</a>
As you see... Below each post ALL 3 categories are listed, I need only to show the categories the post is in and not the others</p>
<p>Thanks</p>
<pre><code><div id="job-manager-job-dashboard">
<h3><?php _e( 'Job listings are shown in the table below.', 'wp-job-manager' ); ?></h3>
<table class="job-manager-jobs">
<thead>
<tr>
<?php foreach ( $job_dashboard_columns as $key => $column ) : ?>
<th class="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $column ); ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php if ( ! $jobs ) : ?>
<tr>
<td colspan="6"><?php _e( 'You do not have any active listings.', 'wp-job-manager' ); ?></td>
</tr>
<?php else : ?>
<?php foreach ( $jobs as $job ) : ?>
<tr>
<?php foreach ( $job_dashboard_columns as $key => $column ) : ?>
<td class="<?php echo esc_attr( $key ); ?>">
<?php if ('job_title' === $key ) : ?>
<?php if ( $job->post_status == 'publish' ) : ?>
<a href="<?php echo get_permalink( $job->ID ); ?>"><?php echo $job->post_title; ?></a><br> Status:
<br><?php $post_id = get_the_ID();
$terms = wp_get_post_terms( $post_id, 'category' );
foreach ( $terms as $term ) {
echo $term->name;
}
?>
<?php else : ?>
<?php echo $job->post_title; ?> <small> (<?php the_job_status( $job ); ?>)</small>
<?php endif; ?>
<ul class="job-dashboard-actions">
<?php
$actions = array();
switch ( $job->post_status ) {
case 'publish' :
$actions['edit'] = array( 'label' => __( 'Edit', 'wp-job-manager' ), 'nonce' => false );
if ( is_position_filled( $job ) ) {
$actions['mark_not_filled'] = array( 'label' => __( 'Not filled', 'wp-job-manager' ), 'nonce' => true );
} else {
$actions['mark_filled'] = array( 'label' => __( 'Filled', 'wp-job-manager' ), 'nonce' => true );
}
break;
case 'pending_payment' :
case 'pending' :
if ( job_manager_user_can_edit_pending_submissions() ) {
$actions['edit'] = array( 'label' => __( 'Edit', 'wp-job-manager' ), 'nonce' => false );
}
break;
}
$actions['delete'] = array( 'label' => __( 'Delete', 'wp-job-manager' ), 'nonce' => true );
$actions = apply_filters( 'job_manager_my_job_actions', $actions, $job );
foreach ( $actions as $action => $value ) {
$action_url = add_query_arg( array( 'action' => $action, 'job_id' => $job->ID ) );
if ( $value['nonce'] ) {
$action_url = wp_nonce_url( $action_url, 'job_manager_my_job_actions' );
}
echo '<li><a href="' . esc_url( $action_url ) . '" class="job-dashboard-action-' . esc_attr( $action ) . '">' . esc_html( $value['label'] ) . '</a></li>';
}
?>
</ul>
<?php elseif ('date' === $key ) : ?>
<?php echo date_i18n( get_option( 'date_format' ), strtotime( $job->post_date ) ); ?>
<?php elseif ('expires' === $key ) : ?>
<?php echo $job->_job_expires ? date_i18n( get_option( 'date_format' ), strtotime( $job->_job_expires ) ) : '&ndash;'; ?>
<?php elseif ('filled' === $key ) : ?>
<?php echo is_position_filled( $job ) ? '&#10004;' : '&ndash;'; ?>
<?php else : ?>
<?php do_action( 'job_manager_job_dashboard_column_' . $key, $job ); ?>
<?php endif; ?>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
<?php get_job_manager_template( 'pagination.php', array( 'max_num_pages' => $max_num_pages ) ); ?>
</code></pre>
<p></p>
| [
{
"answer_id": 242538,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 2,
"selected": false,
"text": "<p>It doesn't matter that you're trying to pull taxonomy from a CPT, you can use <a href=\"https://codex.wordpre... | 2016/10/13 | [
"https://wordpress.stackexchange.com/questions/242536",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104841/"
] | I am currently trying to add a list of categories that a custom post is in (only have 3 categories). by using the code below, I have managed to output ALL categories into a list but what am I missing to filter just the categories that that post is in... Been stuck for days!
Here is the link to better explain - <http://mgmtphdjobs.com/manage-jobs/>
As you see... Below each post ALL 3 categories are listed, I need only to show the categories the post is in and not the others
Thanks
```
<div id="job-manager-job-dashboard">
<h3><?php _e( 'Job listings are shown in the table below.', 'wp-job-manager' ); ?></h3>
<table class="job-manager-jobs">
<thead>
<tr>
<?php foreach ( $job_dashboard_columns as $key => $column ) : ?>
<th class="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $column ); ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php if ( ! $jobs ) : ?>
<tr>
<td colspan="6"><?php _e( 'You do not have any active listings.', 'wp-job-manager' ); ?></td>
</tr>
<?php else : ?>
<?php foreach ( $jobs as $job ) : ?>
<tr>
<?php foreach ( $job_dashboard_columns as $key => $column ) : ?>
<td class="<?php echo esc_attr( $key ); ?>">
<?php if ('job_title' === $key ) : ?>
<?php if ( $job->post_status == 'publish' ) : ?>
<a href="<?php echo get_permalink( $job->ID ); ?>"><?php echo $job->post_title; ?></a><br> Status:
<br><?php $post_id = get_the_ID();
$terms = wp_get_post_terms( $post_id, 'category' );
foreach ( $terms as $term ) {
echo $term->name;
}
?>
<?php else : ?>
<?php echo $job->post_title; ?> <small> (<?php the_job_status( $job ); ?>)</small>
<?php endif; ?>
<ul class="job-dashboard-actions">
<?php
$actions = array();
switch ( $job->post_status ) {
case 'publish' :
$actions['edit'] = array( 'label' => __( 'Edit', 'wp-job-manager' ), 'nonce' => false );
if ( is_position_filled( $job ) ) {
$actions['mark_not_filled'] = array( 'label' => __( 'Not filled', 'wp-job-manager' ), 'nonce' => true );
} else {
$actions['mark_filled'] = array( 'label' => __( 'Filled', 'wp-job-manager' ), 'nonce' => true );
}
break;
case 'pending_payment' :
case 'pending' :
if ( job_manager_user_can_edit_pending_submissions() ) {
$actions['edit'] = array( 'label' => __( 'Edit', 'wp-job-manager' ), 'nonce' => false );
}
break;
}
$actions['delete'] = array( 'label' => __( 'Delete', 'wp-job-manager' ), 'nonce' => true );
$actions = apply_filters( 'job_manager_my_job_actions', $actions, $job );
foreach ( $actions as $action => $value ) {
$action_url = add_query_arg( array( 'action' => $action, 'job_id' => $job->ID ) );
if ( $value['nonce'] ) {
$action_url = wp_nonce_url( $action_url, 'job_manager_my_job_actions' );
}
echo '<li><a href="' . esc_url( $action_url ) . '" class="job-dashboard-action-' . esc_attr( $action ) . '">' . esc_html( $value['label'] ) . '</a></li>';
}
?>
</ul>
<?php elseif ('date' === $key ) : ?>
<?php echo date_i18n( get_option( 'date_format' ), strtotime( $job->post_date ) ); ?>
<?php elseif ('expires' === $key ) : ?>
<?php echo $job->_job_expires ? date_i18n( get_option( 'date_format' ), strtotime( $job->_job_expires ) ) : '–'; ?>
<?php elseif ('filled' === $key ) : ?>
<?php echo is_position_filled( $job ) ? '✔' : '–'; ?>
<?php else : ?>
<?php do_action( 'job_manager_job_dashboard_column_' . $key, $job ); ?>
<?php endif; ?>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
<?php get_job_manager_template( 'pagination.php', array( 'max_num_pages' => $max_num_pages ) ); ?>
``` | EDITS:
```
<div id="job-manager-job-dashboard">
<h3><?php _e( 'Job listings are shown in the table below.', 'wp-job-manager' ); ?></h3>
<table class="job-manager-jobs">
<thead>
<tr>
<?php foreach ( $job_dashboard_columns as $key => $column ) : ?>
<th class="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $column ); ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php if ( ! $jobs ) : ?>
<tr>
<td colspan="6"><?php _e( 'You do not have any active listings.', 'wp-job-manager' ); ?></td>
</tr>
<?php else : ?>
<?php foreach ( $jobs as $job ) : ?>
<tr>
<?php foreach ( $job_dashboard_columns as $key => $column ) : ?>
<td class="<?php echo esc_attr( $key ); ?>">
<?php if ('job_title' === $key ) : ?>
<?php if ( $job->post_status == 'publish' ) : ?>
<a href="<?php echo get_permalink( $job->ID ); ?>"><?php echo $job->post_title; ?></a><br> Status:
<br />
<?php
$terms = wp_get_post_terms( $job->ID, 'job_listing_category' );
foreach ( $terms as $term ) {
echo $term->name;
}
?>
<?php else : ?>
<?php echo $job->post_title; ?> <small> (<?php the_job_status( $job ); ?>)</small>
<?php endif; ?>
<ul class="job-dashboard-actions">
<?php
$actions = array();
switch ( $job->post_status ) {
case 'publish' :
$actions['edit'] = array( 'label' => __( 'Edit', 'wp-job-manager' ), 'nonce' => false );
if ( is_position_filled( $job ) ) {
$actions['mark_not_filled'] = array( 'label' => __( 'Not filled', 'wp-job-manager' ), 'nonce' => true );
} else {
$actions['mark_filled'] = array( 'label' => __( 'Filled', 'wp-job-manager' ), 'nonce' => true );
}
break;
case 'pending_payment' :
case 'pending' :
if ( job_manager_user_can_edit_pending_submissions() ) {
$actions['edit'] = array( 'label' => __( 'Edit', 'wp-job-manager' ), 'nonce' => false );
}
break;
}
$actions['delete'] = array( 'label' => __( 'Delete', 'wp-job-manager' ), 'nonce' => true );
$actions = apply_filters( 'job_manager_my_job_actions', $actions, $job );
foreach ( $actions as $action => $value ) {
$action_url = add_query_arg( array( 'action' => $action, 'job_id' => $job->ID ) );
if ( $value['nonce'] ) {
$action_url = wp_nonce_url( $action_url, 'job_manager_my_job_actions' );
}
echo '<li><a href="' . esc_url( $action_url ) . '" class="job-dashboard-action-' . esc_attr( $action ) . '">' . esc_html( $value['label'] ) . '</a></li>';
}
?>
</ul>
<?php elseif ('date' === $key ) : ?>
<?php echo date_i18n( get_option( 'date_format' ), strtotime( $job->post_date ) ); ?>
<?php elseif ('expires' === $key ) : ?>
<?php echo $job->_job_expires ? date_i18n( get_option( 'date_format' ), strtotime( $job->_job_expires ) ) : '–'; ?>
<?php elseif ('filled' === $key ) : ?>
<?php echo is_position_filled( $job ) ? '✔' : '–'; ?>
<?php else : ?>
<?php do_action( 'job_manager_job_dashboard_column_' . $key, $job ); ?>
<?php endif; ?>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
<?php get_job_manager_template( 'pagination.php', array( 'max_num_pages' => $max_num_pages ) ); ?>
``` |
242,546 | <p>My theme uses this code which I am trying to convert to a shortcode so I can use on custom templates:</p>
<pre><code><div class="x-breadcrumb-wrap">
<div class="x-container max width">
<?php x_breadcrumbs(); ?>
</div>
</div>
</code></pre>
<p>I know I have to add a shortcode like this to my <code>functions.php</code> but can't figure out the syntax.</p>
<pre><code>add_shortcode( 'mycrumbs', 'mytest_breadcrumbs' );
</code></pre>
<p>UPDATE:</p>
<p>For easy of use I only need to call the function x_breadcrumbs. My theme defines this function as:</p>
<pre><code>function x_breadcrumbs() {
if ( x_get_option( 'x_breadcrumb_display' ) ) {
GLOBAL $post;
$is_ltr = ! is_rtl();
$stack = x_get_stack();
$delimiter = x_get_breadcrumb_delimiter();
$home_text = x_get_breadcrumb_home_text();
$home_link = home_url();
$current_before = x_get_breadcrumb_current_before();
$current_after = x_get_breadcrumb_current_after();
$page_title = get_the_title();
$blog_title = get_the_title( get_option( 'page_for_posts', true ) );
if ( ! is_404() ) {
$post_parent = $post->post_parent;
} else {
$post_parent = '';
}
if ( X_WOOCOMMERCE_IS_ACTIVE ) {
$shop_url = x_get_shop_link();
$shop_title = x_get_option( 'x_' . $stack . '_shop_title' );
$shop_link = '<a href="'. $shop_url .'">' . $shop_title . '</a>';
}
echo '<div class="x-breadcrumbs"><a href="' . $home_link . '">' . $home_text . '</a>' . $delimiter;
if ( is_home() ) {
echo $current_before . $blog_title . $current_after;
} elseif ( is_category() ) {
$the_cat = get_category( get_query_var( 'cat' ), false );
if ( $the_cat->parent != 0 ) echo get_category_parents( $the_cat->parent, TRUE, $delimiter );
echo $current_before . single_cat_title( '', false ) . $current_after;
} elseif ( x_is_product_category() ) {
if ( $is_ltr ) {
echo $shop_link . $delimiter . $current_before . single_cat_title( '', false ) . $current_after;
} else {
echo $current_before . single_cat_title( '', false ) . $current_after . $delimiter . $shop_link;
}
} elseif ( x_is_product_tag() ) {
if ( $is_ltr ) {
echo $shop_link . $delimiter . $current_before . single_tag_title( '', false ) . $current_after;
} else {
echo $current_before . single_tag_title( '', false ) . $current_after . $delimiter . $shop_link;
}
} elseif ( is_search() ) {
echo $current_before . __( 'Search Results for ', '__x__' ) . '&#8220;' . get_search_query() . '&#8221;' . $current_after;
} elseif ( is_singular( 'post' ) ) {
if ( get_option( 'page_for_posts' ) == is_front_page() ) {
echo $current_before . $page_title . $current_after;
} else {
if ( $is_ltr ) {
echo '<a href="' . get_permalink( get_option( 'page_for_posts' ) ) . '">' . $blog_title . '</a>' . $delimiter . $current_before . $page_title . $current_after;
} else {
echo $current_before . $page_title . $current_after . $delimiter . '<a href="' . get_permalink( get_option( 'page_for_posts' ) ) . '">' . $blog_title . '</a>';
}
}
} elseif ( x_is_portfolio() ) {
echo $current_before . get_the_title() . $current_after;
} elseif ( x_is_portfolio_item() ) {
$link = x_get_parent_portfolio_link();
$title = x_get_parent_portfolio_title();
if ( $is_ltr ) {
echo '<a href="' . $link . '">' . $title . '</a>' . $delimiter . $current_before . $page_title . $current_after;
} else {
echo $current_before . $page_title . $current_after . $delimiter . '<a href="' . $link . '">' . $title . '</a>';
}
} elseif ( x_is_product() ) {
if ( $is_ltr ) {
echo $shop_link . $delimiter . $current_before . $page_title . $current_after;
} else {
echo $current_before . $page_title . $current_after . $delimiter . $shop_link;
}
} elseif ( x_is_buddypress() ) {
if ( bp_is_group() ) {
echo '<a href="' . bp_get_groups_directory_permalink() . '">' . x_get_option( 'x_buddypress_groups_title' ) . '</a>' . $delimiter . $current_before . x_buddypress_get_the_title() . $current_after;
} elseif ( bp_is_user() ) {
echo '<a href="' . bp_get_members_directory_permalink() . '">' . x_get_option( 'x_buddypress_members_title' ) . '</a>' . $delimiter . $current_before . x_buddypress_get_the_title() . $current_after;
} else {
echo $current_before . x_buddypress_get_the_title() . $current_after;
}
} elseif ( x_is_bbpress() ) {
remove_filter( 'bbp_no_breadcrumb', '__return_true' );
if ( bbp_is_forum_archive() ) {
echo $current_before . bbp_get_forum_archive_title() . $current_after;
} else {
echo bbp_get_breadcrumb();
}
add_filter( 'bbp_no_breadcrumb', '__return_true' );
} elseif ( is_page() && ! $post_parent ) {
echo $current_before . $page_title . $current_after;
} elseif ( is_page() && $post_parent ) {
$parent_id = $post_parent;
$breadcrumbs = array();
if ( is_rtl() ) {
echo $current_before . $page_title . $current_after . $delimiter;
}
while ( $parent_id ) {
$page = get_page( $parent_id );
$breadcrumbs[] = '<a href="' . get_permalink( $page->ID ) . '">' . get_the_title( $page->ID ) . '</a>';
$parent_id = $page->post_parent;
}
if ( $is_ltr ) {
$breadcrumbs = array_reverse( $breadcrumbs );
}
for ( $i = 0; $i < count( $breadcrumbs ); $i++ ) {
echo $breadcrumbs[$i];
if ( $i != count( $breadcrumbs ) -1 ) echo $delimiter;
}
if ( $is_ltr ) {
echo $delimiter . $current_before . $page_title . $current_after;
}
} elseif ( is_tag() ) {
echo $current_before . single_tag_title( '', false ) . $current_after;
} elseif ( is_author() ) {
GLOBAL $author;
$userdata = get_userdata( $author );
echo $current_before . __( 'Posts by ', '__x__' ) . '&#8220;' . $userdata->display_name . $current_after . '&#8221;';
} elseif ( is_404() ) {
echo $current_before . __( '404 (Page Not Found)', '__x__' ) . $current_after;
} elseif ( is_archive() ) {
if ( x_is_shop() ) {
echo $current_before . $shop_title . $current_after;
} else {
echo $current_before . __( 'Archives ', '__x__' ) . $current_after;
}
}
echo '</div>';
}
}
endif;
</code></pre>
| [
{
"answer_id": 242547,
"author": "Nabil Kadimi",
"author_id": 17187,
"author_profile": "https://wordpress.stackexchange.com/users/17187",
"pm_score": 1,
"selected": false,
"text": "<p>This should do it, I used output buffering with <code>ob_start()</code> and <code>ob_get_clean</code>:</... | 2016/10/13 | [
"https://wordpress.stackexchange.com/questions/242546",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] | My theme uses this code which I am trying to convert to a shortcode so I can use on custom templates:
```
<div class="x-breadcrumb-wrap">
<div class="x-container max width">
<?php x_breadcrumbs(); ?>
</div>
</div>
```
I know I have to add a shortcode like this to my `functions.php` but can't figure out the syntax.
```
add_shortcode( 'mycrumbs', 'mytest_breadcrumbs' );
```
UPDATE:
For easy of use I only need to call the function x\_breadcrumbs. My theme defines this function as:
```
function x_breadcrumbs() {
if ( x_get_option( 'x_breadcrumb_display' ) ) {
GLOBAL $post;
$is_ltr = ! is_rtl();
$stack = x_get_stack();
$delimiter = x_get_breadcrumb_delimiter();
$home_text = x_get_breadcrumb_home_text();
$home_link = home_url();
$current_before = x_get_breadcrumb_current_before();
$current_after = x_get_breadcrumb_current_after();
$page_title = get_the_title();
$blog_title = get_the_title( get_option( 'page_for_posts', true ) );
if ( ! is_404() ) {
$post_parent = $post->post_parent;
} else {
$post_parent = '';
}
if ( X_WOOCOMMERCE_IS_ACTIVE ) {
$shop_url = x_get_shop_link();
$shop_title = x_get_option( 'x_' . $stack . '_shop_title' );
$shop_link = '<a href="'. $shop_url .'">' . $shop_title . '</a>';
}
echo '<div class="x-breadcrumbs"><a href="' . $home_link . '">' . $home_text . '</a>' . $delimiter;
if ( is_home() ) {
echo $current_before . $blog_title . $current_after;
} elseif ( is_category() ) {
$the_cat = get_category( get_query_var( 'cat' ), false );
if ( $the_cat->parent != 0 ) echo get_category_parents( $the_cat->parent, TRUE, $delimiter );
echo $current_before . single_cat_title( '', false ) . $current_after;
} elseif ( x_is_product_category() ) {
if ( $is_ltr ) {
echo $shop_link . $delimiter . $current_before . single_cat_title( '', false ) . $current_after;
} else {
echo $current_before . single_cat_title( '', false ) . $current_after . $delimiter . $shop_link;
}
} elseif ( x_is_product_tag() ) {
if ( $is_ltr ) {
echo $shop_link . $delimiter . $current_before . single_tag_title( '', false ) . $current_after;
} else {
echo $current_before . single_tag_title( '', false ) . $current_after . $delimiter . $shop_link;
}
} elseif ( is_search() ) {
echo $current_before . __( 'Search Results for ', '__x__' ) . '“' . get_search_query() . '”' . $current_after;
} elseif ( is_singular( 'post' ) ) {
if ( get_option( 'page_for_posts' ) == is_front_page() ) {
echo $current_before . $page_title . $current_after;
} else {
if ( $is_ltr ) {
echo '<a href="' . get_permalink( get_option( 'page_for_posts' ) ) . '">' . $blog_title . '</a>' . $delimiter . $current_before . $page_title . $current_after;
} else {
echo $current_before . $page_title . $current_after . $delimiter . '<a href="' . get_permalink( get_option( 'page_for_posts' ) ) . '">' . $blog_title . '</a>';
}
}
} elseif ( x_is_portfolio() ) {
echo $current_before . get_the_title() . $current_after;
} elseif ( x_is_portfolio_item() ) {
$link = x_get_parent_portfolio_link();
$title = x_get_parent_portfolio_title();
if ( $is_ltr ) {
echo '<a href="' . $link . '">' . $title . '</a>' . $delimiter . $current_before . $page_title . $current_after;
} else {
echo $current_before . $page_title . $current_after . $delimiter . '<a href="' . $link . '">' . $title . '</a>';
}
} elseif ( x_is_product() ) {
if ( $is_ltr ) {
echo $shop_link . $delimiter . $current_before . $page_title . $current_after;
} else {
echo $current_before . $page_title . $current_after . $delimiter . $shop_link;
}
} elseif ( x_is_buddypress() ) {
if ( bp_is_group() ) {
echo '<a href="' . bp_get_groups_directory_permalink() . '">' . x_get_option( 'x_buddypress_groups_title' ) . '</a>' . $delimiter . $current_before . x_buddypress_get_the_title() . $current_after;
} elseif ( bp_is_user() ) {
echo '<a href="' . bp_get_members_directory_permalink() . '">' . x_get_option( 'x_buddypress_members_title' ) . '</a>' . $delimiter . $current_before . x_buddypress_get_the_title() . $current_after;
} else {
echo $current_before . x_buddypress_get_the_title() . $current_after;
}
} elseif ( x_is_bbpress() ) {
remove_filter( 'bbp_no_breadcrumb', '__return_true' );
if ( bbp_is_forum_archive() ) {
echo $current_before . bbp_get_forum_archive_title() . $current_after;
} else {
echo bbp_get_breadcrumb();
}
add_filter( 'bbp_no_breadcrumb', '__return_true' );
} elseif ( is_page() && ! $post_parent ) {
echo $current_before . $page_title . $current_after;
} elseif ( is_page() && $post_parent ) {
$parent_id = $post_parent;
$breadcrumbs = array();
if ( is_rtl() ) {
echo $current_before . $page_title . $current_after . $delimiter;
}
while ( $parent_id ) {
$page = get_page( $parent_id );
$breadcrumbs[] = '<a href="' . get_permalink( $page->ID ) . '">' . get_the_title( $page->ID ) . '</a>';
$parent_id = $page->post_parent;
}
if ( $is_ltr ) {
$breadcrumbs = array_reverse( $breadcrumbs );
}
for ( $i = 0; $i < count( $breadcrumbs ); $i++ ) {
echo $breadcrumbs[$i];
if ( $i != count( $breadcrumbs ) -1 ) echo $delimiter;
}
if ( $is_ltr ) {
echo $delimiter . $current_before . $page_title . $current_after;
}
} elseif ( is_tag() ) {
echo $current_before . single_tag_title( '', false ) . $current_after;
} elseif ( is_author() ) {
GLOBAL $author;
$userdata = get_userdata( $author );
echo $current_before . __( 'Posts by ', '__x__' ) . '“' . $userdata->display_name . $current_after . '”';
} elseif ( is_404() ) {
echo $current_before . __( '404 (Page Not Found)', '__x__' ) . $current_after;
} elseif ( is_archive() ) {
if ( x_is_shop() ) {
echo $current_before . $shop_title . $current_after;
} else {
echo $current_before . __( 'Archives ', '__x__' ) . $current_after;
}
}
echo '</div>';
}
}
endif;
``` | This should do it, I used output buffering with `ob_start()` and `ob_get_clean`:
```
<?php
/**
* Breadcrumbs based on theme's functions
*
* @author Nabil Kadimi <nabil@kadimi.com>
* @link http://wordpress.stackexchange.com/a/242547/17187
*/
add_action( 'init', function() {
add_shortcode( 'mycrumbs', function() {
/**
* Start capturing output.
*/
ob_start();
?>
<div class="x-breadcrumb-wrap">
<div class="x-container max width">
<?php x_breadcrumbs(); ?>
<?php if ( is_single() || x_is_portfolio_item() ) : ?>
<?php x_entry_navigation(); ?>
<?php endif; ?>
</div>
</div>
<?
/**
* Stop capturing output and return what was captured to WordPress.
*/
return ob_get_clean();
} ); // add_shortcode( 'mycrumbs', closure );
} ); // add_action( 'init', closure );
``` |
242,560 | <p>I have a wordpress website hosted on GoDaddy.</p>
<p>I am an advanced stripe user and have integrated stripe with many Ruby on Rails apps , along with stripe-webhook integration with the Rails. Also i am well versed in how web-hooks work. But recently i was made owner of a wordpress website hosted on GoDaddy and on that website i am supposed to receive stripe payment failed webhook and then trigger an email based on that webhook event. I am not able to make much connect with wordpress and stripe from online resources and need help on how to receive stripe-webhooks in wordpress website i.e where to put code to make that happen etc.</p>
| [
{
"answer_id": 243250,
"author": "AmrataB",
"author_id": 105254,
"author_profile": "https://wordpress.stackexchange.com/users/105254",
"pm_score": 4,
"selected": true,
"text": "<p>I recently had the same problem and pippins stripe integration plugin seemed to answer it but it had a lot o... | 2016/10/13 | [
"https://wordpress.stackexchange.com/questions/242560",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104856/"
] | I have a wordpress website hosted on GoDaddy.
I am an advanced stripe user and have integrated stripe with many Ruby on Rails apps , along with stripe-webhook integration with the Rails. Also i am well versed in how web-hooks work. But recently i was made owner of a wordpress website hosted on GoDaddy and on that website i am supposed to receive stripe payment failed webhook and then trigger an email based on that webhook event. I am not able to make much connect with wordpress and stripe from online resources and need help on how to receive stripe-webhooks in wordpress website i.e where to put code to make that happen etc. | I recently had the same problem and pippins stripe integration plugin seemed to answer it but it had a lot of extra code I did not need so I removed it and made a concise version just for the webhook integration: [WPStripeWebhook](https://github.com/amratab/WPStripeWebhook). README is self explanatory. Basically make changes to includes/stripe\_listener.php for your events. Also attaching readme here as per stackoverflow guidelines:
**Usage:**
1. Copy the complete folder WPStripeWebhook in wp-content/plugins. Go
to website admin page.
2. Activate the WP Stripe webhook plugin for
plugins section.
3. After this Settings will start showing Stripe
webhook settings section. Click on it. In the page fill the stripe
keys and check test mode option if you want to test the plugin.
4. In WPStripeWebhook/includes/stripe\_listener.php, make changes for your
event type and email or whatever you want to do in response to
an event. It currently sends out an email.
**Important notes and suggestions**
For live mode, add stripe webhook endpoint (stripe account -> settings -> account settings -> webhook) like this
>
> htps://yourdomain.com?webhook-listener=stripe
>
>
>
For testing locally on your machine, you can use [Ultrahook](http://www.ultrahook.com/). Its awesome! Set up your keys and username and start ultrahook on your machine using:
>
> ultrahook -k your\_ultrahook\_key stripe 8888
>
>
>
Add a webhook endpoint url in your stripe account similar to this:
>
> htp://stripe.your\_ultrahook\_username.ultrahook.com/your\_wp\_website\_folder\_name/stripe-listener.php?webhook-listener=stripe
>
>
>
And it should start working for you. Also, you might see 404 in ultrahook console. Just ignore it. I would suggest setting up debugging too. It really helps. For debugging, add these to your wp\_config.php
```
define('WP_DEBUG', true);
define( 'WP_DEBUG_LOG', true );
define('WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );
define('SCRIPT_DEBUG', true );
```
After this, you should see a debug.log file in your wp-content folder and it will display errors and warnings and whatever you print using error\_log() |
242,564 | <p>I want to get all users with their respective data. I already get all the users:</p>
<pre><code>$users = array();
$users_query = new WP_User_Query( array(
'role' => 'subscriber',
'orderby' => 'user_registered',
'number' => 8,
'order' => 'DESC',
'fields' => array('ID', 'display_name')
) );
$results = $users_query->get_results();
</code></pre>
<p>But I only get the data from user table: </p>
<pre><code>object(stdClass)#3162 (10) {
["ID"]=>
string(2) "44"
["user_login"]=>
string(13) "usuarioprueba"
["user_nicename"]=>
string(13) "usuarioprueba"
["user_url"]=>
string(0) ""
["user_registered"]=>
string(19) "2016-10-13 16:27:56"
["user_status"]=>
string(1) "0"
["display_name"]=>
string(14) "Usuario Prueba"
} ...
</code></pre>
<p>How do I get also the data from <code>usermeta</code> without having to use a loop like a <code>foreach</code></p>
| [
{
"answer_id": 242575,
"author": "stims",
"author_id": 104727,
"author_profile": "https://wordpress.stackexchange.com/users/104727",
"pm_score": 2,
"selected": false,
"text": "<p>All the metadata should be there, you can access them with magic methods.</p>\n\n<p>If you have a metadatum c... | 2016/10/13 | [
"https://wordpress.stackexchange.com/questions/242564",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38735/"
] | I want to get all users with their respective data. I already get all the users:
```
$users = array();
$users_query = new WP_User_Query( array(
'role' => 'subscriber',
'orderby' => 'user_registered',
'number' => 8,
'order' => 'DESC',
'fields' => array('ID', 'display_name')
) );
$results = $users_query->get_results();
```
But I only get the data from user table:
```
object(stdClass)#3162 (10) {
["ID"]=>
string(2) "44"
["user_login"]=>
string(13) "usuarioprueba"
["user_nicename"]=>
string(13) "usuarioprueba"
["user_url"]=>
string(0) ""
["user_registered"]=>
string(19) "2016-10-13 16:27:56"
["user_status"]=>
string(1) "0"
["display_name"]=>
string(14) "Usuario Prueba"
} ...
```
How do I get also the data from `usermeta` without having to use a loop like a `foreach` | All the metadata should be there, you can access them with magic methods.
If you have a metadatum called with the key `shoes`, you can access it like this
```
$userObject->shoes
``` |
242,580 | <p>I am trying to create a custom role in a wordpress multisite environment. This role is to have the same capabilities as an admin but also have the ability to commit unfiltered HTML like super admins. I have had success in creating the role and set unfiltered_html to true, but the text editor still strips Iframes and other html elements. Below is my PHP code for the new role which I have named 'developer'.</p>
<pre><code>function add_developer()
{
//remove role if it already exists
if( get_role('developer') ){
remove_role( 'developer' );
}
//custom user role for unfiltered_html
$result = add_role('developer', __('Developer' ),
array(
'read' => true,
'activate_plugins' => true,
'delete_others_pages' => true,
'delete_others_posts' => true,
'delete_pages' => true,
'delete_posts' => true,
'delete_private_pages' => true,
'delete_private_posts' => true,
'delete_published_pages' => true,
'delete_published_posts' => true,
'edit_dashboard' => true,
'edit_others_pages' => true,
'edit_others_posts' => true,
'edit_pages' => true,
'edit_posts' => true,
'edit_private_pages' => true,
'edit_private_posts' => true,
'edit_published_pages' => true,
'edit_published_posts' => true,
'edit_theme_options' => true,
'export' => true,
'import' => true,
'list_users' => true,
'manage_categories' => true,
'manage_links' => true,
'manage_options' => true,
'manage_comments' => true,
'promote_users' => true,
'publish_pages' => true,
'publish_posts' => true,
'read_private_pages' => true,
'read_private_posts' => true,
'remove_users' => true,
'switch_themes' => true,
'upload_files' => true,
'unfiltered_html' => true
)
);
if ( null !== $result ) {
echo 'Yay! New role created!';
}
else {
echo 'Oh... the basic_contributor role already exists.';
}
}
</code></pre>
<p>I am working in a team to convert a huge website with thousands of pages and would like to avoid giving everyone super admin access. Is there anyway that I can avoid the html filter for only specific user roles? If not is there anyway to do this for specific users? I would like to avoid altering core and don't mind removing all filtering. I am currently testing this in my functions.php file of my theme but will eventually write a plugin to this.</p>
<p>I am aware of the security risks that will be present due to users being able to post javascript but my team is willing to live with this if we do not have to explicitly give the whole team superadmin access.</p>
<p>Any help is much appreciated!</p>
| [
{
"answer_id": 291464,
"author": "MastaBaba",
"author_id": 43252,
"author_profile": "https://wordpress.stackexchange.com/users/43252",
"pm_score": 1,
"selected": false,
"text": "<p>This had me baffled for a while as well. Not exactly a solution for your problem, but this should get you o... | 2016/10/13 | [
"https://wordpress.stackexchange.com/questions/242580",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104866/"
] | I am trying to create a custom role in a wordpress multisite environment. This role is to have the same capabilities as an admin but also have the ability to commit unfiltered HTML like super admins. I have had success in creating the role and set unfiltered\_html to true, but the text editor still strips Iframes and other html elements. Below is my PHP code for the new role which I have named 'developer'.
```
function add_developer()
{
//remove role if it already exists
if( get_role('developer') ){
remove_role( 'developer' );
}
//custom user role for unfiltered_html
$result = add_role('developer', __('Developer' ),
array(
'read' => true,
'activate_plugins' => true,
'delete_others_pages' => true,
'delete_others_posts' => true,
'delete_pages' => true,
'delete_posts' => true,
'delete_private_pages' => true,
'delete_private_posts' => true,
'delete_published_pages' => true,
'delete_published_posts' => true,
'edit_dashboard' => true,
'edit_others_pages' => true,
'edit_others_posts' => true,
'edit_pages' => true,
'edit_posts' => true,
'edit_private_pages' => true,
'edit_private_posts' => true,
'edit_published_pages' => true,
'edit_published_posts' => true,
'edit_theme_options' => true,
'export' => true,
'import' => true,
'list_users' => true,
'manage_categories' => true,
'manage_links' => true,
'manage_options' => true,
'manage_comments' => true,
'promote_users' => true,
'publish_pages' => true,
'publish_posts' => true,
'read_private_pages' => true,
'read_private_posts' => true,
'remove_users' => true,
'switch_themes' => true,
'upload_files' => true,
'unfiltered_html' => true
)
);
if ( null !== $result ) {
echo 'Yay! New role created!';
}
else {
echo 'Oh... the basic_contributor role already exists.';
}
}
```
I am working in a team to convert a huge website with thousands of pages and would like to avoid giving everyone super admin access. Is there anyway that I can avoid the html filter for only specific user roles? If not is there anyway to do this for specific users? I would like to avoid altering core and don't mind removing all filtering. I am currently testing this in my functions.php file of my theme but will eventually write a plugin to this.
I am aware of the security risks that will be present due to users being able to post javascript but my team is willing to live with this if we do not have to explicitly give the whole team superadmin access.
Any help is much appreciated! | This had me baffled for a while as well. Not exactly a solution for your problem, but this should get you on your way.
```
add_action( 'admin_init', 'my_kses_remove_filters' );
function my_kses_remove_filters() {
$current_user = wp_get_current_user();
if ( my_user_has_role( 'administrator', $current_user ) )
kses_remove_filters();
}
function my_user_has_role( $role = '', $user = null ) {
$user = $user ? new WP_User( $user ) : wp_get_current_user();
if ( empty( $user->roles ) )
return;
if ( in_array( $role, $user->roles ) )
return true;
return;
}
```
This action removes the filters for administrators. First it gets the role of the current user and if the role is 'administrator', it removes the filters on editing content.
This solutions draws heavily from [this page](https://www.thatstevensguy.com/wordpress/wordpress-multisite-unfiltered-html-capability/). |
242,615 | <p>I have a checkbox in the customizer which lets you choose to display content or not. I've got everything to work besides displaying the page content; it echoes the HTML tags but not the WordPress dynamic page date.</p>
<pre><code><?php $servicescontent = get_theme_mod('services-page', 1);
$mod = new WP_Query( array( 'page_id' => $servicescontent ) ); while($mod->have_posts()) : $mod->the_post();?>
<?php $abc = get_theme_mod('services-check', 1);
if( $abc == 1) {
echo ('<div class="section default-bg">
<div class="container">
<h1 id="services" class="text-center title"><?php the_title();?></h1>
<div class="space"></div>
<div class="row">
<?php the_content();?>
<?php endwhile; ?>
</div>
</div>
</div>
<!-- section end -->');}
else{
('');}
?>
</code></pre>
<p>Can someone tell me what characters need escaped? I am trying to teach myself through building a theme from scratch but have not been able to solve this issue myself. When looking at the rendered page's HTML, it looks like the WordPress PHP is being commented out.</p>
| [
{
"answer_id": 291464,
"author": "MastaBaba",
"author_id": 43252,
"author_profile": "https://wordpress.stackexchange.com/users/43252",
"pm_score": 1,
"selected": false,
"text": "<p>This had me baffled for a while as well. Not exactly a solution for your problem, but this should get you o... | 2016/10/14 | [
"https://wordpress.stackexchange.com/questions/242615",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104810/"
] | I have a checkbox in the customizer which lets you choose to display content or not. I've got everything to work besides displaying the page content; it echoes the HTML tags but not the WordPress dynamic page date.
```
<?php $servicescontent = get_theme_mod('services-page', 1);
$mod = new WP_Query( array( 'page_id' => $servicescontent ) ); while($mod->have_posts()) : $mod->the_post();?>
<?php $abc = get_theme_mod('services-check', 1);
if( $abc == 1) {
echo ('<div class="section default-bg">
<div class="container">
<h1 id="services" class="text-center title"><?php the_title();?></h1>
<div class="space"></div>
<div class="row">
<?php the_content();?>
<?php endwhile; ?>
</div>
</div>
</div>
<!-- section end -->');}
else{
('');}
?>
```
Can someone tell me what characters need escaped? I am trying to teach myself through building a theme from scratch but have not been able to solve this issue myself. When looking at the rendered page's HTML, it looks like the WordPress PHP is being commented out. | This had me baffled for a while as well. Not exactly a solution for your problem, but this should get you on your way.
```
add_action( 'admin_init', 'my_kses_remove_filters' );
function my_kses_remove_filters() {
$current_user = wp_get_current_user();
if ( my_user_has_role( 'administrator', $current_user ) )
kses_remove_filters();
}
function my_user_has_role( $role = '', $user = null ) {
$user = $user ? new WP_User( $user ) : wp_get_current_user();
if ( empty( $user->roles ) )
return;
if ( in_array( $role, $user->roles ) )
return true;
return;
}
```
This action removes the filters for administrators. First it gets the role of the current user and if the role is 'administrator', it removes the filters on editing content.
This solutions draws heavily from [this page](https://www.thatstevensguy.com/wordpress/wordpress-multisite-unfiltered-html-capability/). |
242,631 | <p>I wonder, how can I create two separate login pages for two specific users?</p>
<p>Say, for example: I have two users on my site. Admin and Viewer.</p>
<p>On my site's frontend I want to create two different login pages. One login form for Admin only and one login form for Viewer only. I want them to be on a different url too. </p>
<p>I hope you could help me with this issue. Thanks!</p>
| [
{
"answer_id": 242634,
"author": "Cristian Stan",
"author_id": 101642,
"author_profile": "https://wordpress.stackexchange.com/users/101642",
"pm_score": -1,
"selected": false,
"text": "<p>If you are trying to achieve a separate login form on a different page than the one for admins then ... | 2016/10/14 | [
"https://wordpress.stackexchange.com/questions/242631",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104902/"
] | I wonder, how can I create two separate login pages for two specific users?
Say, for example: I have two users on my site. Admin and Viewer.
On my site's frontend I want to create two different login pages. One login form for Admin only and one login form for Viewer only. I want them to be on a different url too.
I hope you could help me with this issue. Thanks! | On-topic answer:
You can just put `<?php wp_login_form(); ?>` into any of your theme templates to render a login form on the front end of your site.
Or make your own shortcode `[loginform]` by putting this into your theme's `functions.php`:
```
function wpse_242473_login_form() {
return wp_login_form( 'echo' => false );
}
add_shortcode( 'loginform', 'wpse_242473_login_form' );
``` |
242,633 | <p>I want to edit the edit-tags.php, particularly the post_tag page. I want to add some content as shown in the pic below.</p>
<p><a href="https://i.stack.imgur.com/kfGmT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kfGmT.png" alt="enter image description here"></a></p>
<p>I have found the way to detect the page with the <a href="https://codex.wordpress.org/Function_Reference/get_current_screen" rel="nofollow noreferrer">get_current_screen</a> function, but I'm clueless what to do next. The only thing I can think of is using Javascript to add the element, but that would be hack-ish.</p>
<p>How do you edit the content in edit-tags.php?</p>
| [
{
"answer_id": 242634,
"author": "Cristian Stan",
"author_id": 101642,
"author_profile": "https://wordpress.stackexchange.com/users/101642",
"pm_score": -1,
"selected": false,
"text": "<p>If you are trying to achieve a separate login form on a different page than the one for admins then ... | 2016/10/14 | [
"https://wordpress.stackexchange.com/questions/242633",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13291/"
] | I want to edit the edit-tags.php, particularly the post\_tag page. I want to add some content as shown in the pic below.
[](https://i.stack.imgur.com/kfGmT.png)
I have found the way to detect the page with the [get\_current\_screen](https://codex.wordpress.org/Function_Reference/get_current_screen) function, but I'm clueless what to do next. The only thing I can think of is using Javascript to add the element, but that would be hack-ish.
How do you edit the content in edit-tags.php? | On-topic answer:
You can just put `<?php wp_login_form(); ?>` into any of your theme templates to render a login form on the front end of your site.
Or make your own shortcode `[loginform]` by putting this into your theme's `functions.php`:
```
function wpse_242473_login_form() {
return wp_login_form( 'echo' => false );
}
add_shortcode( 'loginform', 'wpse_242473_login_form' );
``` |
242,643 | <p><a href="https://i.stack.imgur.com/L25ZN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L25ZN.png" alt="enter image description here"></a>I want to show the count of a particular category, that means how many posts does a particular category have?</p>
<p>I want the number as same as in the picture, but they are echoing like:</p>
<blockquote>
<p>Bathroom Scales (1)<br>
uncategorized (3) </p>
</blockquote>
<p>My code is:</p>
<pre><code>echo wp_list_categories(array(
'show_count' => 'true',
'title_li' => '',
'style' => ''));
</code></pre>
<p>Is there any other way to do this counting thing separately?</p>
| [
{
"answer_id": 242650,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>Just call <code>get_categories()</code>. You'll get back an array of term objects:</p>\n\n<pre><c... | 2016/10/14 | [
"https://wordpress.stackexchange.com/questions/242643",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104901/"
] | [](https://i.stack.imgur.com/L25ZN.png)I want to show the count of a particular category, that means how many posts does a particular category have?
I want the number as same as in the picture, but they are echoing like:
>
> Bathroom Scales (1)
>
> uncategorized (3)
>
>
>
My code is:
```
echo wp_list_categories(array(
'show_count' => 'true',
'title_li' => '',
'style' => ''));
```
Is there any other way to do this counting thing separately? | Just call `get_categories()`. You'll get back an array of term objects:
```
array(
[0] => WP_Term Object
(
[term_id] =>
[name] =>
[slug] =>
[term_group] =>
[term_taxonomy_id] =>
[taxonomy] =>
[description] =>
[parent] =>
[count] =>
[filter] =>
)
)
```
You can process this with `wp_list_pluck` to turn it into an associative array, so for example:
```
$cat_counts = wp_list_pluck( get_categories(), 'count', 'name' );
```
This will return an array like:
```
array(
'Geography' => 5,
'Maths' => 7,
'English' => 3,
)
```
For other taxonomies use `get_terms()` instead. `get_categories()` is really not much more than a wrapper for `get_terms()`.
To show these like the picture you've added to your question, just loop over the array.
```
echo '<dl>';
// use whichever HTML structure you feel is appropriate
foreach ( $cat_counts as $name => $count ) {
echo '<dt>' . $name . '</dt>';
echo '<dd>' . sprintf( "%02d", $count ) . '</dd>';
// use sprintf to specify 2 decimal characters with leading zero if necessary
}
echo '</dl>';
``` |
242,652 | <p>I'm making a limitation for image upload based on @brasofilo <a href="https://wordpress.stackexchange.com/a/73921/13291">excellent snippet</a>. In short, it limits user to only uploading image with minimum dimension.</p>
<p>However I want to apply this only when user is uploading a featured image. I tried using <code>$pagenow</code> as a conditional,</p>
<pre><code>global $pagenow;
if ($pagenow == 'media-upload.php')
add_filter( 'wp_handle_upload_prefilter', 'wpse_28359_block_small_images_upload' );
</code></pre>
<p>But it doesn't work. Any idea here?</p>
| [
{
"answer_id": 242667,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": -1,
"selected": false,
"text": "<p>Add below code to your current theme's functions.php file, and it will limit minimum image d... | 2016/10/14 | [
"https://wordpress.stackexchange.com/questions/242652",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13291/"
] | I'm making a limitation for image upload based on @brasofilo [excellent snippet](https://wordpress.stackexchange.com/a/73921/13291). In short, it limits user to only uploading image with minimum dimension.
However I want to apply this only when user is uploading a featured image. I tried using `$pagenow` as a conditional,
```
global $pagenow;
if ($pagenow == 'media-upload.php')
add_filter( 'wp_handle_upload_prefilter', 'wpse_28359_block_small_images_upload' );
```
But it doesn't work. Any idea here? | Determining if an attachment actually is a *featured image* is easy:
```
get_post_thumbnail_id( get_post() );
```
which is a convenience function around
```
get_post_meta( get_post()->ID, '_thumbnail_id', true );
```
It is a bit more complicated if you know nothing than the File name or Url.
```
add_filter( 'wp_handle_upload_prefilter', function( $file ) {
$url = wp_get_attachment_image_src(
get_post_thumbnail_id( get_post() ),
'post-thumbnail'
);
// Output possible errors
if ( false !== strpos( $url, $file ) ) {
$file['error'] = 'Sorry, but we only allow featured images';
}
return $file;
} );
```
As you can see, I do only compare the current file string with a posts featured image URl. Note that I do not know if this will work, it is not tested and the `wp_handle_upload_prefilter` might be too early.
Another option might be to use the last filter inside `_wp_handle_upload()`:
```
apply_filters( 'wp_handle_upload', array(
'file' => $new_file,
'url' => $url,
'type' => $type
), 'wp_handle_sideload' === $action ? 'sideload' : 'upload' );
```
which handles sideload as well.
In theory I assume it's too early to check if the featured image is actually the featured image before it is set. You might be able to revert the upload once it finished (delete file, reset post meta data), but that is far from elegant.
The meta box itself is registered with `add_meta_box()` and the box callback is `post_thumbnail_meta_box`, which calls `_wp_post_thumbnail_html()` to render the contents. When you look in there, you will see that there is actually a hidden field:
```
$content .= '<input type="hidden" id="_thumbnail_id" name="_thumbnail_id" value="' . esc_attr( $thumbnail_id ? $thumbnail_id : '-1' ) . '" />';
```
Now the `name` is `_thumbnail_id`, which you should be able to fetch with `filter_input()` (good) or with `$_POST['_thumbnail_id']` (bad) inside a callback like `wp_handle_upload_prefilter` to determine if it actually was a featured image:
```
$featID = filter_input( INPUT_POST, '_thumbnail_id', … filters … );
``` |
242,685 | <p>I need to get query results after they have executed </p>
<pre><code> add_filter('query', 'query_recorder_wrapper_wptc');
</code></pre>
<p>I use <code>query</code> filter to get all queries before they executed, I also want after they executed. I exhausted of searching this.</p>
<p>Is there any <code>hooks</code> or script for this?</p>
<p>Thanks</p>
| [
{
"answer_id": 242687,
"author": "stims",
"author_id": 104727,
"author_profile": "https://wordpress.stackexchange.com/users/104727",
"pm_score": 1,
"selected": false,
"text": "<p>What you can do is use the <code>wp</code> action with the global variable <code>$wp_query</code>, like so:</... | 2016/10/14 | [
"https://wordpress.stackexchange.com/questions/242685",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67717/"
] | I need to get query results after they have executed
```
add_filter('query', 'query_recorder_wrapper_wptc');
```
I use `query` filter to get all queries before they executed, I also want after they executed. I exhausted of searching this.
Is there any `hooks` or script for this?
Thanks | Extending the `wpdb` class
--------------------------
We can create the `db.php` file under `wp-content/` directory to override the `wpdb` class to our needs.
I checked this site for such examples and found one by @MarkKaplun [here](https://wordpress.stackexchange.com/a/160819/26350).
Here's an example how one can get access to the *last result*, after each query has run:
```
<?php
/**
* db.php - Override the global $wpdb object to collect all query results
*/
namespace WPSE\Question242685;
class DB extends \wpdb
{
public function __construct( $dbuser, $dbpassword, $dbname, $dbhost )
{
// Parent constructor
parent::__construct( $dbuser, $dbpassword, $dbname, $dbhost );
}
public function query( $query )
{
// Parent query
$val = parent::query( $query );
//----------------------------------------------------------------------
// Edit this to your needs
//
// Warning: It can be slow and resource demanding to collect all results
if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
{
// do something with $this->last_result;
}
//----------------------------------------------------------------------
return $val;
}
} // end class
// Override the global wpdb object
$GLOBALS['wpdb'] = new DB( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
```
Here we assume the `SAVEQUERIES` is defined as `true` in the `wp-config.php` file.
**Note** that collecting *all* the results can be *resource demanding*, so you better only test this on a dev install. |
242,686 | <p>I am creating something which passes featured image URLs to a separate JavaScript file which uses <code>parallax.js</code> to create a parallax background for each entry for an archive page.</p>
<p>This works fine when each post has an image.</p>
<p>I have been working on having a default image where there is no featured image but am having problems on pointing to it. I want to keep the path relative so when I upload to the host there is no need to have an absolute path.</p>
<p>At the moment it goes something like this:</p>
<pre><code>if ( has_featured_image() ) {
$image_link_url = $featured_background_image;
} else {
$image_link_url = get_template_url() . 'images/placeholder_bg.png';
}
</code></pre>
<p>This does not work. How would I get the result I am after? Ideally want to have the function result and string at the end as one single string in a variable.</p>
| [
{
"answer_id": 242689,
"author": "stims",
"author_id": 104727,
"author_profile": "https://wordpress.stackexchange.com/users/104727",
"pm_score": 2,
"selected": true,
"text": "<p>Instead of </p>\n\n<p><code>get_template_url()</code></p>\n\n<p>user</p>\n\n<p><code>get_template_directory_ur... | 2016/10/14 | [
"https://wordpress.stackexchange.com/questions/242686",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101227/"
] | I am creating something which passes featured image URLs to a separate JavaScript file which uses `parallax.js` to create a parallax background for each entry for an archive page.
This works fine when each post has an image.
I have been working on having a default image where there is no featured image but am having problems on pointing to it. I want to keep the path relative so when I upload to the host there is no need to have an absolute path.
At the moment it goes something like this:
```
if ( has_featured_image() ) {
$image_link_url = $featured_background_image;
} else {
$image_link_url = get_template_url() . 'images/placeholder_bg.png';
}
```
This does not work. How would I get the result I am after? Ideally want to have the function result and string at the end as one single string in a variable. | Instead of
`get_template_url()`
user
`get_template_directory_uri()` for parent theme
and
`get_stylesheet_directory_uri()` for child theme or parent theme if not child theme present
NOTE: this will require a slash like so:
```
$image_link_url = get_template_directory_uri() . '/images/placeholder_bg.png';
``` |
242,693 | <p>I have solved the main query:</p>
<p>For WordPress dashboard, I needed the list of all posts related to all post types in:</p>
<pre><code>edit.php?post_type=product
</code></pre>
<p>Using the concept of: </p>
<pre><code>edit.php?post_type=product&showall=true
</code></pre>
<p>With function in backend <code>function.php</code></p>
<pre><code>function show_all_posttypes( $query ) {
if( ! is_admin() ) {
return;
}
if( isset( $_GET, $_GET['showall'] ) && true == $_GET['showall'] ) {
$query->set( 'post_type', array('product', 'second_type_product', 'third_type_product') );
}
}
add_filter( 'pre_get_posts', 'show_all_posttypes' );
</code></pre>
<p>And after that my all posts related to three post types: product, second_type_product, third_type_product is listing very well on URL:</p>
<blockquote>
<p>edit.php?post_type=product&showall=true</p>
</blockquote>
<p>But when I am using its feature to filter on edit.php page with all listed posts then is saying: </p>
<blockquote>
<p>Invalid post type</p>
</blockquote>
<p>I want to achieve every feature support with my list related to multiple post types list on url based on one post type.</p>
<p>Thanks for support!</p>
| [
{
"answer_id": 243222,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 1,
"selected": false,
"text": "<p><code>Invalid Post Type</code> might be shown,whenever you have a mistake(type or etc..) in <code>'product', ... | 2016/10/14 | [
"https://wordpress.stackexchange.com/questions/242693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73730/"
] | I have solved the main query:
For WordPress dashboard, I needed the list of all posts related to all post types in:
```
edit.php?post_type=product
```
Using the concept of:
```
edit.php?post_type=product&showall=true
```
With function in backend `function.php`
```
function show_all_posttypes( $query ) {
if( ! is_admin() ) {
return;
}
if( isset( $_GET, $_GET['showall'] ) && true == $_GET['showall'] ) {
$query->set( 'post_type', array('product', 'second_type_product', 'third_type_product') );
}
}
add_filter( 'pre_get_posts', 'show_all_posttypes' );
```
And after that my all posts related to three post types: product, second\_type\_product, third\_type\_product is listing very well on URL:
>
> edit.php?post\_type=product&showall=true
>
>
>
But when I am using its feature to filter on edit.php page with all listed posts then is saying:
>
> Invalid post type
>
>
>
I want to achieve every feature support with my list related to multiple post types list on url based on one post type.
Thanks for support! | `Invalid Post Type` might be shown,whenever you have a mistake(type or etc..) in `'product', 'second_type_product', 'third_type_product'` . Ensure that you have correct words there. |
242,716 | <p>I'm running WordPress 4.6.1 and I am trying to learn how to filter custom post types by a category taxonomy process. This is very helpful as non-technical folks can easily filter custom post type posts by category in the admin.</p>
<blockquote>
<p>This is my setup...</p>
</blockquote>
<ol>
<li><p>I'm building a child theme off of tweentysixteen</p></li>
<li><p>I created and registered a custom post type in my child <strong>functions.php</strong> file like this...</p>
<pre><code>add_action('init','prowp_register_my_post_types');
function prowp_register_my_post_types() {
register_post_type('products',
array(
'labels' => array (
'name' => 'Products',
'singular_name' => 'Product',
'add_new' => 'Add New Product',
'add_new_item' => 'Add New Product',
'edit_item' => 'Edit this Product',
'new_item' => 'New Product',
'all_items' => 'All My Products'
),
'public' => true,
'show_ui' => true,
'taxonomies' => array (
'category'
),
'supports' => array (
'title',
'revisions',
'editor',
'thumbnail',
'page-attributes',
'custom-fields')
));
}
</code></pre></li>
<li><p>I am now using my registered custom post type in my child index.php file like this:</p>
<pre><code>$pargs = array(
'post_per_page' => '-1',
'post_type' => 'products',
'tax_query' => array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'Specials'
)
);
$myProducts = new WP_Query($pargs);
while ( $myProducts->have_posts() ) : $myProducts->the_post();
get_template_part('template-parts/products',get_post_format());
endwhile;
rewind_posts();
wp_reset_postdata();
</code></pre></li>
<li><p>Finally, from wp-admin, I then created my custom post types posts and assigned the category "Specials" to "one" of my posts. The others are uncategorized. And every page is published.</p></li>
</ol>
<p>...But for some reason, my browser page is listing all my posts from this custom post type, and not just Specials. I'm I doing something wrong?</p>
| [
{
"answer_id": 242720,
"author": "bdtheme",
"author_id": 83330,
"author_profile": "https://wordpress.stackexchange.com/users/83330",
"pm_score": 0,
"selected": false,
"text": "<p>You can try with the following codes:</p>\n\n<pre><code>$terms = wp_get_post_terms( $post->ID, array('cate... | 2016/10/14 | [
"https://wordpress.stackexchange.com/questions/242716",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98671/"
] | I'm running WordPress 4.6.1 and I am trying to learn how to filter custom post types by a category taxonomy process. This is very helpful as non-technical folks can easily filter custom post type posts by category in the admin.
>
> This is my setup...
>
>
>
1. I'm building a child theme off of tweentysixteen
2. I created and registered a custom post type in my child **functions.php** file like this...
```
add_action('init','prowp_register_my_post_types');
function prowp_register_my_post_types() {
register_post_type('products',
array(
'labels' => array (
'name' => 'Products',
'singular_name' => 'Product',
'add_new' => 'Add New Product',
'add_new_item' => 'Add New Product',
'edit_item' => 'Edit this Product',
'new_item' => 'New Product',
'all_items' => 'All My Products'
),
'public' => true,
'show_ui' => true,
'taxonomies' => array (
'category'
),
'supports' => array (
'title',
'revisions',
'editor',
'thumbnail',
'page-attributes',
'custom-fields')
));
}
```
3. I am now using my registered custom post type in my child index.php file like this:
```
$pargs = array(
'post_per_page' => '-1',
'post_type' => 'products',
'tax_query' => array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'Specials'
)
);
$myProducts = new WP_Query($pargs);
while ( $myProducts->have_posts() ) : $myProducts->the_post();
get_template_part('template-parts/products',get_post_format());
endwhile;
rewind_posts();
wp_reset_postdata();
```
4. Finally, from wp-admin, I then created my custom post types posts and assigned the category "Specials" to "one" of my posts. The others are uncategorized. And every page is published.
...But for some reason, my browser page is listing all my posts from this custom post type, and not just Specials. I'm I doing something wrong? | You are doing a little mistake in your `$pargs`
[As per documentation](https://developer.wordpress.org/reference/classes/wp_query/)
>
> **Important Note:** tax\_query takes an array of tax query arguments arrays (it takes an array of arrays). Also you have "post\_per\_page" instead of "posts\_per\_page"
>
>
>
```
$pargs = array(
'posts_per_page' => '-1',
'post_type' => 'products',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'specials'
)
)
)
``` |
242,730 | <p>To avoid collisions with other plugins, one should prefix all global functions, actions and plugins with a unique prefix, e.g.:</p>
<pre><code>function xyz_function_name() { ... }
</code></pre>
<p>The question is, how do I verify that <code>xyz</code> is indeed unique? For instance, Yoast SEO uses <code>wpseo_</code> which I can imagine other SEO plugin could easily use as well. What's the best way to search the available WordPress plugins for potential collisions? Or is there?</p>
| [
{
"answer_id": 243058,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 4,
"selected": true,
"text": "<p>You can use the <a href=\"https://github.com/markjaquith/WordPress-Plugin-Directory-Slurper\">WordPres Plugi... | 2016/10/14 | [
"https://wordpress.stackexchange.com/questions/242730",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12248/"
] | To avoid collisions with other plugins, one should prefix all global functions, actions and plugins with a unique prefix, e.g.:
```
function xyz_function_name() { ... }
```
The question is, how do I verify that `xyz` is indeed unique? For instance, Yoast SEO uses `wpseo_` which I can imagine other SEO plugin could easily use as well. What's the best way to search the available WordPress plugins for potential collisions? Or is there? | You can use the [WordPres Plugin Directory Slurper](https://github.com/markjaquith/WordPress-Plugin-Directory-Slurper) shell script by Mark Jaquith to download the the most recent version of all plugins from the WordPress.org repo. Once the plugins have been downloaded, you can grep for the plugin/hook prefix you want to check, e.g.:
```
grep -r --include=*.php 'wpseo_' ./
```
Unzip the WordPres Plugin Directory Slurper package to to your document root. The default directory name is `WordPress-Plugin-Directory-Slurper` and it contains:
```
/plugins/
/readmes/
/zips/
LICENSE
README.markdown
update
```
Run the bash script by executing `php update` from within the `WordPress-Plugin-Directory-Slurper` directory. Zipped plugins will be downloaded to `/zips` and extracted to `/plugins`. The entire repo is somewhere around 15GB and will take several hours to download the first time.
The contents of the `update` script:
```
#!/usr/bin/php
<?php
$args = $argv;
$cmd = array_shift( $args );
$type = 'all';
if ( !empty( $args[0] ) ) {
$type = $args[0];
}
switch ( $type ) {
case 'readme':
$directory = 'readmes';
$download = 'readmes/%s.readme';
$url = 'http://plugins.svn.wordpress.org/%s/trunk/readme.txt';
break;
case 'all':
$directory = 'plugins';
$download = 'zips/%s.zip';
$url = 'http://downloads.wordpress.org/plugin/%s.latest-stable.zip?nostats=1';
break;
default:
echo $cmd . ": invalid command\r\n";
echo 'Usage: php ' . $cmd . " [command]\r\n\r\n";
echo "Available commands:\r\n";
echo " all - Downloads full plugin zips\r\n";
echo " readme - Downloads plugin readmes only\r\n";
die();
}
echo "Determining most recent SVN revision...\r\n";
try {
$changelog = @file_get_contents( 'http://plugins.trac.wordpress.org/log/?format=changelog&stop_rev=HEAD' );
if ( !$changelog )
throw new Exception( 'Could not fetch the SVN changelog' );
preg_match( '#\[([0-9]+)\]#', $changelog, $matches );
if ( !$matches[1] )
throw new Exception( 'Could not determine most recent revision.' );
} catch ( Exception $e ) {
die( $e->getMessage() . "\r\n" );
}
$svn_last_revision = (int) $matches[1];
echo "Most recent SVN revision: " . $svn_last_revision . "\r\n";
if ( file_exists( $directory . '/.last-revision' ) ) {
$last_revision = (int) file_get_contents( $directory . '/.last-revision' );
echo "Last synced revision: " . $last_revision . "\r\n";
} else {
$last_revision = false;
echo "You have not yet performed a successful sync. Settle in. This will take a while.\r\n";
}
$start_time = time();
if ( $last_revision != $svn_last_revision ) {
if ( $last_revision ) {
$changelog_url = sprintf( 'http://plugins.trac.wordpress.org/log/?verbose=on&mode=follow_copy&format=changelog&rev=%d&limit=%d', $svn_last_revision, $svn_last_revision - $last_revision );
$changes = file_get_contents( $changelog_url );
preg_match_all( '#^' . "\t" . '*\* ([^/A-Z ]+)[ /].* \((added|modified|deleted|moved|copied)\)' . "\n" . '#m', $changes, $matches );
$plugins = array_unique( $matches[1] );
} else {
$plugins = file_get_contents( 'http://svn.wp-plugins.org/' );
preg_match_all( '#<li><a href="([^/]+)/">([^/]+)/</a></li>#', $plugins, $matches );
$plugins = $matches[1];
}
foreach ( $plugins as $plugin ) {
$plugin = urldecode( $plugin );
echo "Updating " . $plugin;
$output = null; $return = null;
exec( 'wget -q -np -O ' . escapeshellarg( sprintf($download, $plugin) ) . ' ' . escapeshellarg( sprintf($url, $plugin) ) . ' > /dev/null', $output, $return );
if ( $return === 0 && file_exists( sprintf($download, $plugin) ) ) {
if ($type === 'all') {
if ( file_exists( 'plugins/' . $plugin ) )
exec( 'rm -rf ' . escapeshellarg( 'plugins/' . $plugin ) );
exec( 'unzip -o -d plugins ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );
exec( 'rm -rf ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );
}
} else {
echo '... download failed.';
}
echo "\r\n";
}
if ( file_put_contents( $directory . '/.last-revision', $svn_last_revision ) )
echo "[CLEANUP] Updated $directory/.last-revision to " . $svn_last_revision . "\r\n";
else
echo "[ERROR] Could not update $directory/.last-revision to " . $svn_last_revision . "\r\n";
}
$end_time = time();
$minutes = ( $end_time - $start_time ) / 60;
$seconds = ( $end_time - $start_time ) % 60;
echo "[SUCCESS] Done updating plugins!\r\n";
echo "It took " . number_format($minutes) . " minute" . ( $minutes == 1 ? '' : 's' ) . " and " . $seconds . " second" . ( $seconds == 1 ? '' : 's' ) . " to update ". count($plugins) ." plugin" . ( count($plugins) == 1 ? '' : 's') . "\r\n";
echo "[DONE]\r\n";
```
If you'd like to download all of the most recent approved themes, there's a script for that too: [WordPress Theme Directory Slurper](https://github.com/aaronjorbin/WordPress-Theme-Directory-Slurper) by Aaron Jorbin.
These shell scripts are designed for a Unix system. If you're using Windows, you can run the Plugin/Theme Directory Slurper scripts using cygwin. |
242,764 | <p>I'm completely stuck and would very much appreciate some pointers/advise.</p>
<p><strong>The problem</strong>: I want to create a search function that will let me filter Japanese onsen by their amenities, e.g. parking, sauna, bedrock bath, etc. which are stored as metadata in the post (a checklist).</p>
<p>I have registered these amenities as a metadata checklist in the post with the following code:</p>
<pre><code>add_filter( 'rwmb_meta_boxes', 'onsen_register_meta_boxes' );
function onsen_register_meta_boxes( $meta_boxes ) {
$meta_boxes[] = array(
'title' => esc_html__( 'Amenities', 'onsen' ),
'context' => 'side',
'fields' => array(
// CHECKBOX LIST
array(
'id' => "{$prefix}checkbox_list",
'type' => 'checkbox_list',
// Options of checkboxes, in format 'value' => 'Label'
'options' => array(
'sauna' => esc_html__( 'Sauna', 'onsen' ),
'parking' => esc_html__( 'Parking', 'onsen' ),
'natural' => esc_html__( 'Natural', 'onsen' ),
'food' => esc_html__( 'Food', 'onsen' ),
'station' => esc_html__( 'Close to Station', 'onsen' ),
'towel' => esc_html__( 'Towel', 'onsen' ),
'bedrock' => esc_html__( 'Bedrock Bath', 'onsen' ),
'shampoo' => esc_html__( 'Shampoo', 'onsen' ),
'rest' => esc_html__( 'Rest Area', 'onsen' ),
'tattoo' => esc_html__( 'Tattoo OK', 'onsen' ),
),
),
),
);
return $meta_boxes;
}
</code></pre>
<p>This code gives me the checklist in the back-end and so I can easily check the relevant boxes for a given onsen. I understand that I need to create a front-end user form with a checklist of all the amenities, but I do not know how to create the $args for the WP_Query on a custom search page because as it's a checklist there may be multiple or no data points to grab... Any help would be very much appreciated.</p>
| [
{
"answer_id": 243058,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 4,
"selected": true,
"text": "<p>You can use the <a href=\"https://github.com/markjaquith/WordPress-Plugin-Directory-Slurper\">WordPres Plugi... | 2016/10/15 | [
"https://wordpress.stackexchange.com/questions/242764",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62598/"
] | I'm completely stuck and would very much appreciate some pointers/advise.
**The problem**: I want to create a search function that will let me filter Japanese onsen by their amenities, e.g. parking, sauna, bedrock bath, etc. which are stored as metadata in the post (a checklist).
I have registered these amenities as a metadata checklist in the post with the following code:
```
add_filter( 'rwmb_meta_boxes', 'onsen_register_meta_boxes' );
function onsen_register_meta_boxes( $meta_boxes ) {
$meta_boxes[] = array(
'title' => esc_html__( 'Amenities', 'onsen' ),
'context' => 'side',
'fields' => array(
// CHECKBOX LIST
array(
'id' => "{$prefix}checkbox_list",
'type' => 'checkbox_list',
// Options of checkboxes, in format 'value' => 'Label'
'options' => array(
'sauna' => esc_html__( 'Sauna', 'onsen' ),
'parking' => esc_html__( 'Parking', 'onsen' ),
'natural' => esc_html__( 'Natural', 'onsen' ),
'food' => esc_html__( 'Food', 'onsen' ),
'station' => esc_html__( 'Close to Station', 'onsen' ),
'towel' => esc_html__( 'Towel', 'onsen' ),
'bedrock' => esc_html__( 'Bedrock Bath', 'onsen' ),
'shampoo' => esc_html__( 'Shampoo', 'onsen' ),
'rest' => esc_html__( 'Rest Area', 'onsen' ),
'tattoo' => esc_html__( 'Tattoo OK', 'onsen' ),
),
),
),
);
return $meta_boxes;
}
```
This code gives me the checklist in the back-end and so I can easily check the relevant boxes for a given onsen. I understand that I need to create a front-end user form with a checklist of all the amenities, but I do not know how to create the $args for the WP\_Query on a custom search page because as it's a checklist there may be multiple or no data points to grab... Any help would be very much appreciated. | You can use the [WordPres Plugin Directory Slurper](https://github.com/markjaquith/WordPress-Plugin-Directory-Slurper) shell script by Mark Jaquith to download the the most recent version of all plugins from the WordPress.org repo. Once the plugins have been downloaded, you can grep for the plugin/hook prefix you want to check, e.g.:
```
grep -r --include=*.php 'wpseo_' ./
```
Unzip the WordPres Plugin Directory Slurper package to to your document root. The default directory name is `WordPress-Plugin-Directory-Slurper` and it contains:
```
/plugins/
/readmes/
/zips/
LICENSE
README.markdown
update
```
Run the bash script by executing `php update` from within the `WordPress-Plugin-Directory-Slurper` directory. Zipped plugins will be downloaded to `/zips` and extracted to `/plugins`. The entire repo is somewhere around 15GB and will take several hours to download the first time.
The contents of the `update` script:
```
#!/usr/bin/php
<?php
$args = $argv;
$cmd = array_shift( $args );
$type = 'all';
if ( !empty( $args[0] ) ) {
$type = $args[0];
}
switch ( $type ) {
case 'readme':
$directory = 'readmes';
$download = 'readmes/%s.readme';
$url = 'http://plugins.svn.wordpress.org/%s/trunk/readme.txt';
break;
case 'all':
$directory = 'plugins';
$download = 'zips/%s.zip';
$url = 'http://downloads.wordpress.org/plugin/%s.latest-stable.zip?nostats=1';
break;
default:
echo $cmd . ": invalid command\r\n";
echo 'Usage: php ' . $cmd . " [command]\r\n\r\n";
echo "Available commands:\r\n";
echo " all - Downloads full plugin zips\r\n";
echo " readme - Downloads plugin readmes only\r\n";
die();
}
echo "Determining most recent SVN revision...\r\n";
try {
$changelog = @file_get_contents( 'http://plugins.trac.wordpress.org/log/?format=changelog&stop_rev=HEAD' );
if ( !$changelog )
throw new Exception( 'Could not fetch the SVN changelog' );
preg_match( '#\[([0-9]+)\]#', $changelog, $matches );
if ( !$matches[1] )
throw new Exception( 'Could not determine most recent revision.' );
} catch ( Exception $e ) {
die( $e->getMessage() . "\r\n" );
}
$svn_last_revision = (int) $matches[1];
echo "Most recent SVN revision: " . $svn_last_revision . "\r\n";
if ( file_exists( $directory . '/.last-revision' ) ) {
$last_revision = (int) file_get_contents( $directory . '/.last-revision' );
echo "Last synced revision: " . $last_revision . "\r\n";
} else {
$last_revision = false;
echo "You have not yet performed a successful sync. Settle in. This will take a while.\r\n";
}
$start_time = time();
if ( $last_revision != $svn_last_revision ) {
if ( $last_revision ) {
$changelog_url = sprintf( 'http://plugins.trac.wordpress.org/log/?verbose=on&mode=follow_copy&format=changelog&rev=%d&limit=%d', $svn_last_revision, $svn_last_revision - $last_revision );
$changes = file_get_contents( $changelog_url );
preg_match_all( '#^' . "\t" . '*\* ([^/A-Z ]+)[ /].* \((added|modified|deleted|moved|copied)\)' . "\n" . '#m', $changes, $matches );
$plugins = array_unique( $matches[1] );
} else {
$plugins = file_get_contents( 'http://svn.wp-plugins.org/' );
preg_match_all( '#<li><a href="([^/]+)/">([^/]+)/</a></li>#', $plugins, $matches );
$plugins = $matches[1];
}
foreach ( $plugins as $plugin ) {
$plugin = urldecode( $plugin );
echo "Updating " . $plugin;
$output = null; $return = null;
exec( 'wget -q -np -O ' . escapeshellarg( sprintf($download, $plugin) ) . ' ' . escapeshellarg( sprintf($url, $plugin) ) . ' > /dev/null', $output, $return );
if ( $return === 0 && file_exists( sprintf($download, $plugin) ) ) {
if ($type === 'all') {
if ( file_exists( 'plugins/' . $plugin ) )
exec( 'rm -rf ' . escapeshellarg( 'plugins/' . $plugin ) );
exec( 'unzip -o -d plugins ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );
exec( 'rm -rf ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );
}
} else {
echo '... download failed.';
}
echo "\r\n";
}
if ( file_put_contents( $directory . '/.last-revision', $svn_last_revision ) )
echo "[CLEANUP] Updated $directory/.last-revision to " . $svn_last_revision . "\r\n";
else
echo "[ERROR] Could not update $directory/.last-revision to " . $svn_last_revision . "\r\n";
}
$end_time = time();
$minutes = ( $end_time - $start_time ) / 60;
$seconds = ( $end_time - $start_time ) % 60;
echo "[SUCCESS] Done updating plugins!\r\n";
echo "It took " . number_format($minutes) . " minute" . ( $minutes == 1 ? '' : 's' ) . " and " . $seconds . " second" . ( $seconds == 1 ? '' : 's' ) . " to update ". count($plugins) ." plugin" . ( count($plugins) == 1 ? '' : 's') . "\r\n";
echo "[DONE]\r\n";
```
If you'd like to download all of the most recent approved themes, there's a script for that too: [WordPress Theme Directory Slurper](https://github.com/aaronjorbin/WordPress-Theme-Directory-Slurper) by Aaron Jorbin.
These shell scripts are designed for a Unix system. If you're using Windows, you can run the Plugin/Theme Directory Slurper scripts using cygwin. |
242,773 | <p>I need to pass arrays to a function from multiple functions. I am using <code>apply_filters_ref_array()</code> for that. The problem is it only accepts the array passed from highest priority callbak. Here is the scenario: </p>
<pre><code>//First Callbak
function first_callback() {
$html['abc'] = 'xyz';
return $html;
}
add_filter( 'process_args', 'first_callback' );
//Second Callbak
function second_callback() {
$html['def'] = 'uvw';
return $html;
}
add_filter( 'process_args', 'second_callback' );
//Third Callbak
function third_callback() {
$html['ghi'] = 'rst';
return $html;
}
add_filter( 'process_args', 'third_callback' );
//Callbak that processes $args
function process_args( $args ) {
$args = apply_filters_ref_array( 'process_args', $args );
print_r( $args );
}
</code></pre>
<p>Now, the <code>print_r( $args );</code> prints the array passed from the last function.</p>
<pre><code>Array (
[ghi] => rst
)
</code></pre>
<p>I need to print it as: </p>
<pre><code>Array (
[abc] => xyz
[def] => uvw
[ghi] => rst
)
</code></pre>
<p>How do I do that?</p>
<p>Thanks </p>
<p><strong>EDIT:</strong><br>
Current code I am working with </p>
<pre><code>function pwpus_input_field_text( $field, $inputs, $html=array() ) {
$html['text'] = '<input id="'.$field['id'].'" type="text" class="pwpus-text-input pwpus-input-size-'.$field['size'].'" name="'.$field['name'].'" value="'.$field['default'].'">';
return $html;
}
add_filter( 'pwpus_input_fields', 'pwpus_input_field_text' );
function pwpus_input_field_tel( $field, $inputs, $html=array() ) {
$html['tel'] = '<input id="'.$field['id'].'" type="tel" class="pwpus-text-input pwpus-input-size-'.$field['size'].'" name="'.$field['name'].'" value="'.$field['default'].'">';
return $html;
}
add_filter( 'pwpus_input_fields', 'pwpus_input_field_tel' );
function pwpus_input_field_email( $field, $inputs, $html=array() ) {
$html['email'] = '<input id="'.$field['id'].'" type="email" class="pwpus-text-input pwpus-input-size-'.$field['size'].'" name="'.$field['name'].'" value="'.$field['default'].'">';
return $html;
}
add_filter( 'pwpus_input_fields', 'pwpus_input_field_email' );
function pwpus_shortcode_form( $fields, $inputs=array() ) {
$inputs = apply_filters_ref_array( 'pwpus_input_fields', $inputs );
//$inputs = do_action( 'pwpus_input_fields' );
if ( array_key_exists( 'class', $fields ) && $fields['class'] != '' ) {
$class = ' ' . $fields['class'];
} else {
$class = '';
}
if ( array_key_exists( 'callback', $fields ) && $fields['callback'] != '' ) {
$callback = $fields['callback'];
} else {
$callback = 'pwusp_nocallback';
}
$html = '<form id="pwpus-shortcode-form" class="pwpus-shortcode-form' . $class . '" action="pwpus_parse_scform">';
$html .= '<table class="pwpus-shortcode-form-table">';
if ( array_key_exists( 'fields', $fields ) && is_array($fields['fields']) ) {
foreach ( $fields['fields'] as $field ) {
//$html .= pwpus_fields( $field );
$html .= '<tr id="field-'. $field['id'] .'"><td><label for="'. $field['name'] .'">'. $field['label'] .'</label></td><td>:</td><td>' . $inputs[ $field['type'] ]. '<span class="pwpus-field-desc">'. $field['desc'] .'</span></td></tr>';
}
}
$html .= '<input type="hidden" name="callback" value="'. $callback .'">';
$html .= wp_nonce_field( 'pwpus-shortcode-nonce', 'pwpus-shortcode-nonce', false );
$html .= '</table>';
$html .= '<div class="pwpus-form-buttons"><button type="submit" id="pwpus-scform-submit" class="pwpus-scform-submit">' . __( 'Generate Shortcode', 'purewp' ) . '</button><button type="reset" id="pwpus-scform-reset" class="pwpus-scform-reset">' . __( 'Reset', 'purewp' ) . '</button></div>';
$html .= '</form>';
//return $html;
print_r( $inputs );
}
</code></pre>
| [
{
"answer_id": 243058,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 4,
"selected": true,
"text": "<p>You can use the <a href=\"https://github.com/markjaquith/WordPress-Plugin-Directory-Slurper\">WordPres Plugi... | 2016/10/15 | [
"https://wordpress.stackexchange.com/questions/242773",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26991/"
] | I need to pass arrays to a function from multiple functions. I am using `apply_filters_ref_array()` for that. The problem is it only accepts the array passed from highest priority callbak. Here is the scenario:
```
//First Callbak
function first_callback() {
$html['abc'] = 'xyz';
return $html;
}
add_filter( 'process_args', 'first_callback' );
//Second Callbak
function second_callback() {
$html['def'] = 'uvw';
return $html;
}
add_filter( 'process_args', 'second_callback' );
//Third Callbak
function third_callback() {
$html['ghi'] = 'rst';
return $html;
}
add_filter( 'process_args', 'third_callback' );
//Callbak that processes $args
function process_args( $args ) {
$args = apply_filters_ref_array( 'process_args', $args );
print_r( $args );
}
```
Now, the `print_r( $args );` prints the array passed from the last function.
```
Array (
[ghi] => rst
)
```
I need to print it as:
```
Array (
[abc] => xyz
[def] => uvw
[ghi] => rst
)
```
How do I do that?
Thanks
**EDIT:**
Current code I am working with
```
function pwpus_input_field_text( $field, $inputs, $html=array() ) {
$html['text'] = '<input id="'.$field['id'].'" type="text" class="pwpus-text-input pwpus-input-size-'.$field['size'].'" name="'.$field['name'].'" value="'.$field['default'].'">';
return $html;
}
add_filter( 'pwpus_input_fields', 'pwpus_input_field_text' );
function pwpus_input_field_tel( $field, $inputs, $html=array() ) {
$html['tel'] = '<input id="'.$field['id'].'" type="tel" class="pwpus-text-input pwpus-input-size-'.$field['size'].'" name="'.$field['name'].'" value="'.$field['default'].'">';
return $html;
}
add_filter( 'pwpus_input_fields', 'pwpus_input_field_tel' );
function pwpus_input_field_email( $field, $inputs, $html=array() ) {
$html['email'] = '<input id="'.$field['id'].'" type="email" class="pwpus-text-input pwpus-input-size-'.$field['size'].'" name="'.$field['name'].'" value="'.$field['default'].'">';
return $html;
}
add_filter( 'pwpus_input_fields', 'pwpus_input_field_email' );
function pwpus_shortcode_form( $fields, $inputs=array() ) {
$inputs = apply_filters_ref_array( 'pwpus_input_fields', $inputs );
//$inputs = do_action( 'pwpus_input_fields' );
if ( array_key_exists( 'class', $fields ) && $fields['class'] != '' ) {
$class = ' ' . $fields['class'];
} else {
$class = '';
}
if ( array_key_exists( 'callback', $fields ) && $fields['callback'] != '' ) {
$callback = $fields['callback'];
} else {
$callback = 'pwusp_nocallback';
}
$html = '<form id="pwpus-shortcode-form" class="pwpus-shortcode-form' . $class . '" action="pwpus_parse_scform">';
$html .= '<table class="pwpus-shortcode-form-table">';
if ( array_key_exists( 'fields', $fields ) && is_array($fields['fields']) ) {
foreach ( $fields['fields'] as $field ) {
//$html .= pwpus_fields( $field );
$html .= '<tr id="field-'. $field['id'] .'"><td><label for="'. $field['name'] .'">'. $field['label'] .'</label></td><td>:</td><td>' . $inputs[ $field['type'] ]. '<span class="pwpus-field-desc">'. $field['desc'] .'</span></td></tr>';
}
}
$html .= '<input type="hidden" name="callback" value="'. $callback .'">';
$html .= wp_nonce_field( 'pwpus-shortcode-nonce', 'pwpus-shortcode-nonce', false );
$html .= '</table>';
$html .= '<div class="pwpus-form-buttons"><button type="submit" id="pwpus-scform-submit" class="pwpus-scform-submit">' . __( 'Generate Shortcode', 'purewp' ) . '</button><button type="reset" id="pwpus-scform-reset" class="pwpus-scform-reset">' . __( 'Reset', 'purewp' ) . '</button></div>';
$html .= '</form>';
//return $html;
print_r( $inputs );
}
``` | You can use the [WordPres Plugin Directory Slurper](https://github.com/markjaquith/WordPress-Plugin-Directory-Slurper) shell script by Mark Jaquith to download the the most recent version of all plugins from the WordPress.org repo. Once the plugins have been downloaded, you can grep for the plugin/hook prefix you want to check, e.g.:
```
grep -r --include=*.php 'wpseo_' ./
```
Unzip the WordPres Plugin Directory Slurper package to to your document root. The default directory name is `WordPress-Plugin-Directory-Slurper` and it contains:
```
/plugins/
/readmes/
/zips/
LICENSE
README.markdown
update
```
Run the bash script by executing `php update` from within the `WordPress-Plugin-Directory-Slurper` directory. Zipped plugins will be downloaded to `/zips` and extracted to `/plugins`. The entire repo is somewhere around 15GB and will take several hours to download the first time.
The contents of the `update` script:
```
#!/usr/bin/php
<?php
$args = $argv;
$cmd = array_shift( $args );
$type = 'all';
if ( !empty( $args[0] ) ) {
$type = $args[0];
}
switch ( $type ) {
case 'readme':
$directory = 'readmes';
$download = 'readmes/%s.readme';
$url = 'http://plugins.svn.wordpress.org/%s/trunk/readme.txt';
break;
case 'all':
$directory = 'plugins';
$download = 'zips/%s.zip';
$url = 'http://downloads.wordpress.org/plugin/%s.latest-stable.zip?nostats=1';
break;
default:
echo $cmd . ": invalid command\r\n";
echo 'Usage: php ' . $cmd . " [command]\r\n\r\n";
echo "Available commands:\r\n";
echo " all - Downloads full plugin zips\r\n";
echo " readme - Downloads plugin readmes only\r\n";
die();
}
echo "Determining most recent SVN revision...\r\n";
try {
$changelog = @file_get_contents( 'http://plugins.trac.wordpress.org/log/?format=changelog&stop_rev=HEAD' );
if ( !$changelog )
throw new Exception( 'Could not fetch the SVN changelog' );
preg_match( '#\[([0-9]+)\]#', $changelog, $matches );
if ( !$matches[1] )
throw new Exception( 'Could not determine most recent revision.' );
} catch ( Exception $e ) {
die( $e->getMessage() . "\r\n" );
}
$svn_last_revision = (int) $matches[1];
echo "Most recent SVN revision: " . $svn_last_revision . "\r\n";
if ( file_exists( $directory . '/.last-revision' ) ) {
$last_revision = (int) file_get_contents( $directory . '/.last-revision' );
echo "Last synced revision: " . $last_revision . "\r\n";
} else {
$last_revision = false;
echo "You have not yet performed a successful sync. Settle in. This will take a while.\r\n";
}
$start_time = time();
if ( $last_revision != $svn_last_revision ) {
if ( $last_revision ) {
$changelog_url = sprintf( 'http://plugins.trac.wordpress.org/log/?verbose=on&mode=follow_copy&format=changelog&rev=%d&limit=%d', $svn_last_revision, $svn_last_revision - $last_revision );
$changes = file_get_contents( $changelog_url );
preg_match_all( '#^' . "\t" . '*\* ([^/A-Z ]+)[ /].* \((added|modified|deleted|moved|copied)\)' . "\n" . '#m', $changes, $matches );
$plugins = array_unique( $matches[1] );
} else {
$plugins = file_get_contents( 'http://svn.wp-plugins.org/' );
preg_match_all( '#<li><a href="([^/]+)/">([^/]+)/</a></li>#', $plugins, $matches );
$plugins = $matches[1];
}
foreach ( $plugins as $plugin ) {
$plugin = urldecode( $plugin );
echo "Updating " . $plugin;
$output = null; $return = null;
exec( 'wget -q -np -O ' . escapeshellarg( sprintf($download, $plugin) ) . ' ' . escapeshellarg( sprintf($url, $plugin) ) . ' > /dev/null', $output, $return );
if ( $return === 0 && file_exists( sprintf($download, $plugin) ) ) {
if ($type === 'all') {
if ( file_exists( 'plugins/' . $plugin ) )
exec( 'rm -rf ' . escapeshellarg( 'plugins/' . $plugin ) );
exec( 'unzip -o -d plugins ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );
exec( 'rm -rf ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );
}
} else {
echo '... download failed.';
}
echo "\r\n";
}
if ( file_put_contents( $directory . '/.last-revision', $svn_last_revision ) )
echo "[CLEANUP] Updated $directory/.last-revision to " . $svn_last_revision . "\r\n";
else
echo "[ERROR] Could not update $directory/.last-revision to " . $svn_last_revision . "\r\n";
}
$end_time = time();
$minutes = ( $end_time - $start_time ) / 60;
$seconds = ( $end_time - $start_time ) % 60;
echo "[SUCCESS] Done updating plugins!\r\n";
echo "It took " . number_format($minutes) . " minute" . ( $minutes == 1 ? '' : 's' ) . " and " . $seconds . " second" . ( $seconds == 1 ? '' : 's' ) . " to update ". count($plugins) ." plugin" . ( count($plugins) == 1 ? '' : 's') . "\r\n";
echo "[DONE]\r\n";
```
If you'd like to download all of the most recent approved themes, there's a script for that too: [WordPress Theme Directory Slurper](https://github.com/aaronjorbin/WordPress-Theme-Directory-Slurper) by Aaron Jorbin.
These shell scripts are designed for a Unix system. If you're using Windows, you can run the Plugin/Theme Directory Slurper scripts using cygwin. |
242,780 | <p>I currently use this conditional code...</p>
<pre><code><?php
if ( $paged < 2 ) echo 'some text';
else echo 'some other text';
?>
</code></pre>
<p>I need to add some more php between the 'if' and 'else'...</p>
<pre><code><p>Text...<?php $published_posts = wp_count_posts('item'); echo $published_posts->publish; ?> text... <?php echo do_shortcode("[count]"); ?> text.</p>
</code></pre>
<p>...so that it'll be something like this...</p>
<pre><code><?php
if ( $paged < 2 ) echo 'some text';
<p>Text...<?php $published_posts = wp_count_posts('item'); echo $published_posts->publish; ?> text... <?php echo do_shortcode("[count]"); ?> text.</p>
else echo 'some other text';
?>
</code></pre>
<p>That obviously won't work, but I don't know enough to recode it.</p>
| [
{
"answer_id": 242782,
"author": "Anish",
"author_id": 104559,
"author_profile": "https://wordpress.stackexchange.com/users/104559",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n<p><a href=\"http://php.net/manual/en/control-structures.if.php\" rel=\"nofollow noreferrer\">As PH... | 2016/10/15 | [
"https://wordpress.stackexchange.com/questions/242780",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103213/"
] | I currently use this conditional code...
```
<?php
if ( $paged < 2 ) echo 'some text';
else echo 'some other text';
?>
```
I need to add some more php between the 'if' and 'else'...
```
<p>Text...<?php $published_posts = wp_count_posts('item'); echo $published_posts->publish; ?> text... <?php echo do_shortcode("[count]"); ?> text.</p>
```
...so that it'll be something like this...
```
<?php
if ( $paged < 2 ) echo 'some text';
<p>Text...<?php $published_posts = wp_count_posts('item'); echo $published_posts->publish; ?> text... <?php echo do_shortcode("[count]"); ?> text.</p>
else echo 'some other text';
?>
```
That obviously won't work, but I don't know enough to recode it. | >
> [As PHP documentation says](http://php.net/manual/en/control-structures.if.php)
>
>
> Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group.
>
>
>
So You have to use `curly braces` `{}` to add more statement within `if` `else`
```
<?php if ( $paged < 2 ) {
echo 'some text';
?>
<p>
Text...
<?php $published_posts = wp_count_posts('item');
echo $published_posts->publish; ?>
text...
<?php echo do_shortcode("[count]"); ?>
text.
</p>
<?php
} else {
echo 'some other text';
} ?>
``` |
242,786 | <p>I have some specific functionality based on post's tags.</p>
<p>How can I send email to admin@blog.com when:
1) user add new post with specific tag (ex. 'tag1')
OR
2) user edit his pending post and assign specific tag ('tag1')?</p>
<p>Thanks =) </p>
| [
{
"answer_id": 242782,
"author": "Anish",
"author_id": 104559,
"author_profile": "https://wordpress.stackexchange.com/users/104559",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n<p><a href=\"http://php.net/manual/en/control-structures.if.php\" rel=\"nofollow noreferrer\">As PH... | 2016/10/15 | [
"https://wordpress.stackexchange.com/questions/242786",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I have some specific functionality based on post's tags.
How can I send email to admin@blog.com when:
1) user add new post with specific tag (ex. 'tag1')
OR
2) user edit his pending post and assign specific tag ('tag1')?
Thanks =) | >
> [As PHP documentation says](http://php.net/manual/en/control-structures.if.php)
>
>
> Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group.
>
>
>
So You have to use `curly braces` `{}` to add more statement within `if` `else`
```
<?php if ( $paged < 2 ) {
echo 'some text';
?>
<p>
Text...
<?php $published_posts = wp_count_posts('item');
echo $published_posts->publish; ?>
text...
<?php echo do_shortcode("[count]"); ?>
text.
</p>
<?php
} else {
echo 'some other text';
} ?>
``` |
242,813 | <p>I've searched all day for this and couldn't find a plugin that allow me to restrict the access to specific pages in the wp-admin backed by user role.</p>
<p>Example: I have several users on my website and I want them to only see the pages that they are allowed to edit. I've done this manually by code and it's working (see code below), but I wanted a plugin that allowed me to the same thing. </p>
<p>Why? Because I have a support team that manages the site and they can't code. Every time I need to add a page or allow someone else on some page I need to manually go there and edit that file. </p>
<p>The closest I came to a solution was the Pages by User Role plugin, on CodeCanyon, but it doesn't work on the backend. Something similar that works on the backend would be great.</p>
<pre><code>if(current_user_can('custom-editor')){
function allowed_pages_custom_e($query) {
global $pagenow,$post_type;
if (is_admin() && $pagenow=='edit.php' && $post_type =='page') {
$query->query_vars['post__in'] = array('11678');
}
}
add_filter( 'parse_query', 'allowed_pages_custom_e' );
}
</code></pre>
| [
{
"answer_id": 242818,
"author": "Sumesh S",
"author_id": 104736,
"author_profile": "https://wordpress.stackexchange.com/users/104736",
"pm_score": 0,
"selected": false,
"text": "<p>Use Advanced Access Manager ( <a href=\"https://wordpress.org/plugins/advanced-access-manager/\" rel=\"nof... | 2016/10/16 | [
"https://wordpress.stackexchange.com/questions/242813",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104993/"
] | I've searched all day for this and couldn't find a plugin that allow me to restrict the access to specific pages in the wp-admin backed by user role.
Example: I have several users on my website and I want them to only see the pages that they are allowed to edit. I've done this manually by code and it's working (see code below), but I wanted a plugin that allowed me to the same thing.
Why? Because I have a support team that manages the site and they can't code. Every time I need to add a page or allow someone else on some page I need to manually go there and edit that file.
The closest I came to a solution was the Pages by User Role plugin, on CodeCanyon, but it doesn't work on the backend. Something similar that works on the backend would be great.
```
if(current_user_can('custom-editor')){
function allowed_pages_custom_e($query) {
global $pagenow,$post_type;
if (is_admin() && $pagenow=='edit.php' && $post_type =='page') {
$query->query_vars['post__in'] = array('11678');
}
}
add_filter( 'parse_query', 'allowed_pages_custom_e' );
}
``` | ```
if( is_admin() ) {
add_filter( 'init', 'custom_restrict_pages_from_admin' );
}
function custom_restrict_pages_from_admin() {
global $pagenow;
$arr = array(
'update-core.php',
'edit.php'
);
if( custom_check_user_roles() && in_array( $pagenow , $arr ) ) {
//echo some custom messages or call the functions
} else {
echo 'This page has restricted access to specific roles';
wp_die();
}
}
function custom_check_user_roles() {
//restrict pages by user role
if( current_user_can( 'administrator' ) || current_user_can( 'editor' ) )
return true;
else {
echo 'Not allowed!';
wp_die();
}
}
``` |
242,814 | <p>I want to use a URL to display content in the frontend. For example</p>
<ul>
<li>domain.tld/?myplugin&confirmey=KEY&mail=MAIL</li>
</ul>
<p>But i don´t know the way(s?) to do it. For example i have a user that clicks on a confirm link in an E-Mail and i want to show him a page with some text.</p>
<ul>
<li>Must exist a real page in WordPres?</li>
<li>Can i include a frontend.php in the existing Content-Area of the Theme to display my text?</li>
<li>Are there other solutions?</li>
</ul>
<p>I don't want a user of the plugin to manually add a page or even add code to their themes functions.php</p>
| [
{
"answer_id": 242818,
"author": "Sumesh S",
"author_id": 104736,
"author_profile": "https://wordpress.stackexchange.com/users/104736",
"pm_score": 0,
"selected": false,
"text": "<p>Use Advanced Access Manager ( <a href=\"https://wordpress.org/plugins/advanced-access-manager/\" rel=\"nof... | 2016/10/16 | [
"https://wordpress.stackexchange.com/questions/242814",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54551/"
] | I want to use a URL to display content in the frontend. For example
* domain.tld/?myplugin&confirmey=KEY&mail=MAIL
But i don´t know the way(s?) to do it. For example i have a user that clicks on a confirm link in an E-Mail and i want to show him a page with some text.
* Must exist a real page in WordPres?
* Can i include a frontend.php in the existing Content-Area of the Theme to display my text?
* Are there other solutions?
I don't want a user of the plugin to manually add a page or even add code to their themes functions.php | ```
if( is_admin() ) {
add_filter( 'init', 'custom_restrict_pages_from_admin' );
}
function custom_restrict_pages_from_admin() {
global $pagenow;
$arr = array(
'update-core.php',
'edit.php'
);
if( custom_check_user_roles() && in_array( $pagenow , $arr ) ) {
//echo some custom messages or call the functions
} else {
echo 'This page has restricted access to specific roles';
wp_die();
}
}
function custom_check_user_roles() {
//restrict pages by user role
if( current_user_can( 'administrator' ) || current_user_can( 'editor' ) )
return true;
else {
echo 'Not allowed!';
wp_die();
}
}
``` |
242,834 | <p>The WordPress area of my site (which has registration) is in for example <code>mydomain.com/members/</code></p>
<p>I would like to know from a PHP routine in my <code>public_html</code> root <code>mydomain.com/offers.php</code> if they are logged into the WordPress area <code>mydomain.com/members</code></p>
<p>I have tried various things to try and get this to work without success. <code>get_current_user_id()</code> always returns <code>0</code> or <code>is_user_logged_in()</code> returns <code>false</code>.</p>
<p>If it helps to give me the correct solution, my WordPress uses the theme MH-Magazine, and uses the plugins Paid Memberships Pro and Theme My Login.</p>
| [
{
"answer_id": 242818,
"author": "Sumesh S",
"author_id": 104736,
"author_profile": "https://wordpress.stackexchange.com/users/104736",
"pm_score": 0,
"selected": false,
"text": "<p>Use Advanced Access Manager ( <a href=\"https://wordpress.org/plugins/advanced-access-manager/\" rel=\"nof... | 2016/10/16 | [
"https://wordpress.stackexchange.com/questions/242834",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105005/"
] | The WordPress area of my site (which has registration) is in for example `mydomain.com/members/`
I would like to know from a PHP routine in my `public_html` root `mydomain.com/offers.php` if they are logged into the WordPress area `mydomain.com/members`
I have tried various things to try and get this to work without success. `get_current_user_id()` always returns `0` or `is_user_logged_in()` returns `false`.
If it helps to give me the correct solution, my WordPress uses the theme MH-Magazine, and uses the plugins Paid Memberships Pro and Theme My Login. | ```
if( is_admin() ) {
add_filter( 'init', 'custom_restrict_pages_from_admin' );
}
function custom_restrict_pages_from_admin() {
global $pagenow;
$arr = array(
'update-core.php',
'edit.php'
);
if( custom_check_user_roles() && in_array( $pagenow , $arr ) ) {
//echo some custom messages or call the functions
} else {
echo 'This page has restricted access to specific roles';
wp_die();
}
}
function custom_check_user_roles() {
//restrict pages by user role
if( current_user_can( 'administrator' ) || current_user_can( 'editor' ) )
return true;
else {
echo 'Not allowed!';
wp_die();
}
}
``` |
242,839 | <p>I have this shortcode</p>
<pre><code>[broo_user_badges username=""]
</code></pre>
<p>and I have to put username between " "
But, username is in URL: /author/peter.
So, when page domain.com/author/peter was loaded, on that page this shortcode should be generated:</p>
<pre><code>[broo_user_badges username="peter"]
</code></pre>
<p>I found this </p>
<pre><code>add_shortcode('name', 'get_name');
function get_name() {
return $_GET['name'];
}
</code></pre>
<p>here <a href="https://wordpress.stackexchange.com/questions/155588/how-to-get-url-param-to-shortcode">How to get URL param to shortcode?</a>
but I do not understand how to use that on my case (/author/peter url structure).</p>
<p>Edit: plugin <a href="https://wordpress.org/plugins/badgearoo/" rel="nofollow noreferrer">https://wordpress.org/plugins/badgearoo/</a></p>
| [
{
"answer_id": 242818,
"author": "Sumesh S",
"author_id": 104736,
"author_profile": "https://wordpress.stackexchange.com/users/104736",
"pm_score": 0,
"selected": false,
"text": "<p>Use Advanced Access Manager ( <a href=\"https://wordpress.org/plugins/advanced-access-manager/\" rel=\"nof... | 2016/10/16 | [
"https://wordpress.stackexchange.com/questions/242839",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105007/"
] | I have this shortcode
```
[broo_user_badges username=""]
```
and I have to put username between " "
But, username is in URL: /author/peter.
So, when page domain.com/author/peter was loaded, on that page this shortcode should be generated:
```
[broo_user_badges username="peter"]
```
I found this
```
add_shortcode('name', 'get_name');
function get_name() {
return $_GET['name'];
}
```
here [How to get URL param to shortcode?](https://wordpress.stackexchange.com/questions/155588/how-to-get-url-param-to-shortcode)
but I do not understand how to use that on my case (/author/peter url structure).
Edit: plugin <https://wordpress.org/plugins/badgearoo/> | ```
if( is_admin() ) {
add_filter( 'init', 'custom_restrict_pages_from_admin' );
}
function custom_restrict_pages_from_admin() {
global $pagenow;
$arr = array(
'update-core.php',
'edit.php'
);
if( custom_check_user_roles() && in_array( $pagenow , $arr ) ) {
//echo some custom messages or call the functions
} else {
echo 'This page has restricted access to specific roles';
wp_die();
}
}
function custom_check_user_roles() {
//restrict pages by user role
if( current_user_can( 'administrator' ) || current_user_can( 'editor' ) )
return true;
else {
echo 'Not allowed!';
wp_die();
}
}
``` |
242,872 | <p>I'm having a really annoying problem with <a href="https://wordpress.org/plugins/black-studio-tinymce-widget/" rel="nofollow">Black Studio TinyMCE Widget</a> in Wordpress, wherein the plugin always adds paragraph <code>p</code> tags around any text, image, link, object when switching from Visual editing mode to HTML mode within the widget. </p>
<p>The switch is often needed to refine some details in the code, but then most formatting is corrupted by these unwanted <code>p</code> tags. </p>
<p>Has anyone had this experience and/or has a solution?</p>
| [
{
"answer_id": 242818,
"author": "Sumesh S",
"author_id": 104736,
"author_profile": "https://wordpress.stackexchange.com/users/104736",
"pm_score": 0,
"selected": false,
"text": "<p>Use Advanced Access Manager ( <a href=\"https://wordpress.org/plugins/advanced-access-manager/\" rel=\"nof... | 2016/10/16 | [
"https://wordpress.stackexchange.com/questions/242872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105038/"
] | I'm having a really annoying problem with [Black Studio TinyMCE Widget](https://wordpress.org/plugins/black-studio-tinymce-widget/) in Wordpress, wherein the plugin always adds paragraph `p` tags around any text, image, link, object when switching from Visual editing mode to HTML mode within the widget.
The switch is often needed to refine some details in the code, but then most formatting is corrupted by these unwanted `p` tags.
Has anyone had this experience and/or has a solution? | ```
if( is_admin() ) {
add_filter( 'init', 'custom_restrict_pages_from_admin' );
}
function custom_restrict_pages_from_admin() {
global $pagenow;
$arr = array(
'update-core.php',
'edit.php'
);
if( custom_check_user_roles() && in_array( $pagenow , $arr ) ) {
//echo some custom messages or call the functions
} else {
echo 'This page has restricted access to specific roles';
wp_die();
}
}
function custom_check_user_roles() {
//restrict pages by user role
if( current_user_can( 'administrator' ) || current_user_can( 'editor' ) )
return true;
else {
echo 'Not allowed!';
wp_die();
}
}
``` |
242,875 | <p>When I insert this code in functions.php:</p>
<pre><code>add_action( 'pre_get_posts', 'my_change_sort_order');
function my_change_sort_order($query){
if(is_post_type_archive()):
//If you wanted it for the archive of a custom post type use: is_post_type_archive( $post_type )
//Set the order ASC or DESC
$query->set( 'order', 'ASC' );
//Set the orderby
$query->set( 'orderby', 'title' );
endif;
};
</code></pre>
<p>sorting occurs throughout the site, I just need to on the main page in which the ID 540. Tried options with</p>
<pre><code>if(is_post_type_archive() && is_page('540')):
</code></pre>
<p>and</p>
<pre><code>if(is_post_type_archive() && is_home()):
</code></pre>
<p>and</p>
<pre><code>if(is_post_type_archive() && is_front_page()):
</code></pre>
<p>all not working.
please help anybody, thanks!</p>
| [
{
"answer_id": 242878,
"author": "Robbert",
"author_id": 25834,
"author_profile": "https://wordpress.stackexchange.com/users/25834",
"pm_score": 0,
"selected": false,
"text": "<p>Since you only want to hook into the posts on your homepage, I think you only need something like this:</p>\n... | 2016/10/16 | [
"https://wordpress.stackexchange.com/questions/242875",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105039/"
] | When I insert this code in functions.php:
```
add_action( 'pre_get_posts', 'my_change_sort_order');
function my_change_sort_order($query){
if(is_post_type_archive()):
//If you wanted it for the archive of a custom post type use: is_post_type_archive( $post_type )
//Set the order ASC or DESC
$query->set( 'order', 'ASC' );
//Set the orderby
$query->set( 'orderby', 'title' );
endif;
};
```
sorting occurs throughout the site, I just need to on the main page in which the ID 540. Tried options with
```
if(is_post_type_archive() && is_page('540')):
```
and
```
if(is_post_type_archive() && is_home()):
```
and
```
if(is_post_type_archive() && is_front_page()):
```
all not working.
please help anybody, thanks! | Since you only want to hook into the posts on your homepage, I think you only need something like this:
```
<?php
add_action( 'pre_get_posts', 'my_change_sort_order');
function my_change_sort_order( $query ){
if ( ! is_admin() && $query->is_main_query() ) :
if ( is_front_page() ) :
//Set the order ASC or DESC
$query->set( 'order', 'ASC' );
//Set the orderby
$query->set( 'orderby', 'title' );
endif;
endif;
}
?>
``` |
242,896 | <p>How can we apply filters only to posts with a specific custom post type? I would like some of my custom posts to start out in HTML mode for their editors. This is what I am working with so far...</p>
<pre><code> add_filter( 'wp_default_editor', create_function('', 'return "html";') );
</code></pre>
| [
{
"answer_id": 242895,
"author": "mike510a",
"author_id": 103274,
"author_profile": "https://wordpress.stackexchange.com/users/103274",
"pm_score": 0,
"selected": false,
"text": "<p>One way is to modify the file: <em>front-page.php</em> in your child theme's folder and include this:</p>\... | 2016/10/17 | [
"https://wordpress.stackexchange.com/questions/242896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98671/"
] | How can we apply filters only to posts with a specific custom post type? I would like some of my custom posts to start out in HTML mode for their editors. This is what I am working with so far...
```
add_filter( 'wp_default_editor', create_function('', 'return "html";') );
``` | You can do it in two different ways
01) Go to Settings > Reading and make the designation change and click “save changes”.
[](https://i.stack.imgur.com/98af1.png)
02) Go to Appearance > Customize > Static Front Page and choose to display the latest posts. |
242,910 | <p>I created a search form which searching by category filter and keyword input. The search form code is here-</p>
<pre><code><form action="<?php bloginfo('url'); ?>" method="get" role="search" class="dropdown-form">
<div class="input-group">
<span class="input-group-addon">
<?php
wp_dropdown_categories(array(
'show_option_all' => 'all categories',
'class' => 'search_cats'
));
?>
</span>
<input type="search" class="form-control" placeholder="<?php esc_html_e('Search anything...', 'onepro'); ?>" name="s">
<span class="input-group-addon">
<button type="submit"><i class="ion-android-arrow-forward"></i></button>
</span>
</div>
</form>
</code></pre>
<p>Then I added the <code>pre_get_posts</code> hook to bottom of the <code>functions.php</code> file-</p>
<pre><code>add_action('pre_get_posts', function() {
global $wp_query;
if (is_search()) {
$cat = intval($_GET['cat']);
$cat = ($cat > 0) ? $cat : '';
$wp_query->query_vars['cat'] = $cat;
}
});
</code></pre>
<p>The search form is working as well. But the bellow notice is appearing on where I used <code>WP_Query()</code> to display the post categories -</p>
<blockquote>
<p>Notice: is_search was called incorrectly. Conditional query tags do not work before the query is run. Before then, they always return false. Please see Debugging in WordPress for more information. (This message was added in version 3.1.0.) in C:\xampp\htdocs\onepro\wp-includes\functions.php on line 3996</p>
</blockquote>
<p>Here is the query code- </p>
<pre><code> global $wp_query;
global $paged;
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => $atts['show_posts'],
'paged' => $paged,
));
if ( $wp_query->have_posts() ) :
$all_cat_slug = array();
while ( $wp_query->have_posts() ) : $wp_query->the_post();
$category = get_the_category();
foreach( $category as $cat ){
array_push($all_cat_slug, $cat->slug);
}
endwhile;
$all_cat_slug = array_unique( $all_cat_slug );
endif;
<!--Portfolio Filter-->
<div class="row filters_row text-left">
<ul class="nav navbar-nav" id="blogs_filters">
<li data-filter="*" class="active"><?php echo esc_html__('all', 'onepro-essential'); ?></li>
<?php
foreach( $all_cat_slug as $cs ){
$catname = get_category_by_slug( $cs );
echo '<li data-filter=".category-'. $cs .'">'. $catname->name .'</li>';
}
?>
</ul>
</div>
</code></pre>
<p>The error notice occurs before the categories shown
The error screenshot-
<a href="https://i.stack.imgur.com/lHeq3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lHeq3.png" alt="enter image description here"></a>
How can I fix this issue?</p>
| [
{
"answer_id": 242947,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<h2>The <em>Why</em> part</h2>\n\n<p>In the core <code>is_search()</code> function there's a check if the global... | 2016/10/17 | [
"https://wordpress.stackexchange.com/questions/242910",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75264/"
] | I created a search form which searching by category filter and keyword input. The search form code is here-
```
<form action="<?php bloginfo('url'); ?>" method="get" role="search" class="dropdown-form">
<div class="input-group">
<span class="input-group-addon">
<?php
wp_dropdown_categories(array(
'show_option_all' => 'all categories',
'class' => 'search_cats'
));
?>
</span>
<input type="search" class="form-control" placeholder="<?php esc_html_e('Search anything...', 'onepro'); ?>" name="s">
<span class="input-group-addon">
<button type="submit"><i class="ion-android-arrow-forward"></i></button>
</span>
</div>
</form>
```
Then I added the `pre_get_posts` hook to bottom of the `functions.php` file-
```
add_action('pre_get_posts', function() {
global $wp_query;
if (is_search()) {
$cat = intval($_GET['cat']);
$cat = ($cat > 0) ? $cat : '';
$wp_query->query_vars['cat'] = $cat;
}
});
```
The search form is working as well. But the bellow notice is appearing on where I used `WP_Query()` to display the post categories -
>
> Notice: is\_search was called incorrectly. Conditional query tags do not work before the query is run. Before then, they always return false. Please see Debugging in WordPress for more information. (This message was added in version 3.1.0.) in C:\xampp\htdocs\onepro\wp-includes\functions.php on line 3996
>
>
>
Here is the query code-
```
global $wp_query;
global $paged;
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => $atts['show_posts'],
'paged' => $paged,
));
if ( $wp_query->have_posts() ) :
$all_cat_slug = array();
while ( $wp_query->have_posts() ) : $wp_query->the_post();
$category = get_the_category();
foreach( $category as $cat ){
array_push($all_cat_slug, $cat->slug);
}
endwhile;
$all_cat_slug = array_unique( $all_cat_slug );
endif;
<!--Portfolio Filter-->
<div class="row filters_row text-left">
<ul class="nav navbar-nav" id="blogs_filters">
<li data-filter="*" class="active"><?php echo esc_html__('all', 'onepro-essential'); ?></li>
<?php
foreach( $all_cat_slug as $cs ){
$catname = get_category_by_slug( $cs );
echo '<li data-filter=".category-'. $cs .'">'. $catname->name .'</li>';
}
?>
</ul>
</div>
```
The error notice occurs before the categories shown
The error screenshot-
[](https://i.stack.imgur.com/lHeq3.png)
How can I fix this issue? | The *Why* part
--------------
In the core `is_search()` function there's a check if the global `$wp_query` is set:
```
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__,
__( 'Conditional query tags do not work before the query is run.
Before then, they always return false.' ), '3.1.0' );
return false;
}
```
Note that you're unsetting it with:
```
$wp_query = null;
```
just before you create a new `WP_Query` subquery, that calls `is_search()` when `pre_get_posts` fires.
That's when the `_doing_it_wrong()` is activated.
Workaround
----------
Always try to use the *main query*, instead of extra `WP_Query` sub-queries if possible, to avoid running extra database queries.
To target the main search query in the front-end, we can use:
```
add_action('pre_get_posts', function( \WP_Query $q ) {
if (
! is_admin() // Only target the front-end
&& $q->is_main_query() // Target the main query
&& $q->is_search() // Target a search query
) {
// do stuff
}
});
``` |
242,914 | <p>I want to make a search button that search only within my website.</p>
<ol>
<li>Do I need external PHP or PERL script? </li>
<li>Can it done by JavaScript? </li>
<li>Or simply by HTML.</li>
</ol>
<p>I tried to create a form using HTML:</p>
<pre><code><form>
<input type="search" name="banner_search" class="banner-text-box" >
<input type="submit" name="" value="SEARCH" class="banner-text-btn">
</form>
</code></pre>
| [
{
"answer_id": 242916,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>You can use WordPress's internal search by calling the <a href=\"https://developer.wordpress.org/reference/f... | 2016/10/17 | [
"https://wordpress.stackexchange.com/questions/242914",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104901/"
] | I want to make a search button that search only within my website.
1. Do I need external PHP or PERL script?
2. Can it done by JavaScript?
3. Or simply by HTML.
I tried to create a form using HTML:
```
<form>
<input type="search" name="banner_search" class="banner-text-box" >
<input type="submit" name="" value="SEARCH" class="banner-text-btn">
</form>
``` | You can use WordPress's internal search by calling the [`get_search_form()`](https://developer.wordpress.org/reference/functions/get_search_form/) function:
```
<?php get_search_form(); ?>
```
`get_search_form()` will use a default HTML form, but you can create your own custom form by adding a `searchform.php` file to your theme. |
242,929 | <p>I want to display all post with its own category. I tried but the loop is fetching all existing categories. Here is my code:</p>
<pre><code><?php //query to echo the categories
$cat_counts = wp_list_pluck( get_categories(),'count', 'name' );?>
<?php foreach ( $cat_counts as $name => $count ) {?>
<li>
<a href="#"><?php echo $name;?></a>
<a href='#' class='pull-right'><?php echo sprintf( "%02d", $count ) ;?></a><br/>
</li>
</code></pre>
| [
{
"answer_id": 242916,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>You can use WordPress's internal search by calling the <a href=\"https://developer.wordpress.org/reference/f... | 2016/10/17 | [
"https://wordpress.stackexchange.com/questions/242929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104901/"
] | I want to display all post with its own category. I tried but the loop is fetching all existing categories. Here is my code:
```
<?php //query to echo the categories
$cat_counts = wp_list_pluck( get_categories(),'count', 'name' );?>
<?php foreach ( $cat_counts as $name => $count ) {?>
<li>
<a href="#"><?php echo $name;?></a>
<a href='#' class='pull-right'><?php echo sprintf( "%02d", $count ) ;?></a><br/>
</li>
``` | You can use WordPress's internal search by calling the [`get_search_form()`](https://developer.wordpress.org/reference/functions/get_search_form/) function:
```
<?php get_search_form(); ?>
```
`get_search_form()` will use a default HTML form, but you can create your own custom form by adding a `searchform.php` file to your theme. |
242,938 | <p>I would like to use both the <code>meta_query</code> and the <code>tax_query</code>, but using the following I can get results for the <code>meta_query</code>. What am I doing wrong?</p>
<pre><code>$wp_query = new WP_Query( array(
'post_type' => 'whatson',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'sc_related_venues_title',
'value' => $location,
'compare' => 'LIKE' ,
'field' => 'title',
),
),
'tax_query' => array(
array(
'taxonomy' => 'eventtype',
'terms' => $event_type,
'field' => 'slug',
'compare' => 'LIKE'
),
),
'posts_per_page' => '10',
'paged' => $paged
) );
</code></pre>
| [
{
"answer_id": 242940,
"author": "MrFox",
"author_id": 69240,
"author_profile": "https://wordpress.stackexchange.com/users/69240",
"pm_score": 2,
"selected": false,
"text": "<p>Would you believe it, as soon as I posted this I remembered I asked a question about a query last year. I had a... | 2016/10/17 | [
"https://wordpress.stackexchange.com/questions/242938",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69240/"
] | I would like to use both the `meta_query` and the `tax_query`, but using the following I can get results for the `meta_query`. What am I doing wrong?
```
$wp_query = new WP_Query( array(
'post_type' => 'whatson',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'sc_related_venues_title',
'value' => $location,
'compare' => 'LIKE' ,
'field' => 'title',
),
),
'tax_query' => array(
array(
'taxonomy' => 'eventtype',
'terms' => $event_type,
'field' => 'slug',
'compare' => 'LIKE'
),
),
'posts_per_page' => '10',
'paged' => $paged
) );
``` | Would you believe it, as soon as I posted this I remembered I asked a question about a query last year. I had a look over it and I've adapted my new query like so:
```
$category_slug = filter_input(
INPUT_GET,
'eventtype',
FILTER_SANITIZE_STRING
);
$cat_query = [];
if( $event_type ){
$cat_query = [
[
'taxonomy' => 'eventtype',
'field' => 'slug',
'terms' => $event_type
]
];
}
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => array('whatson'),
'post_status' => 'publish',
'tax_query' => $cat_query,
'meta_query' => array(
array(
'key' => 'sc_related_venues_title',
'value' => $location,
'compare' => 'LIKE' ,
'field' => 'title',
),
),
'orderby' => 'date',
'order' => 'desc',
'posts_per_page' => '10',
'paged' => $paged,
);
$wp_query = new WP_Query( $args);
``` |
243,012 | <p>I'm disabling <a href="https://hackertarget.com/wordpress-user-enumeration/" rel="nofollow">user enumeration</a> for security purposes in order to prevent usernames from being revealed by looking up the user IDs. Instead, whenever someone tried to find out the username by their ID, such as visiting the following:</p>
<pre><code>http://example.com?author=1
</code></pre>
<p>It will redirect them to the homepage. After searching around, I've found two plugins which have this function, but both of them use slightly different logics to check if someone is trying to enumerate:</p>
<h3>Logic #1</h3>
<pre><code>if ( preg_match( '/(wp-comments-post)/', $_SERVER['REQUEST_URI'] ) === 0 && ! empty( $_REQUEST['author'] ) ) {
# Redirect to homepage...
}
</code></pre>
<h3>Logic #2</h3>
<pre><code>if ( ! preg_match( '/(wp-comments-post)/', $_SERVER['REQUEST_URI'] ) && ! empty( $_REQUEST['author'] ) && ( int ) $_REQUEST['author'] ) {
# Redirect to homepage...
}
</code></pre>
<p>Both logics work, but I'm wondering which one is more effective and what they are doing differently.</p>
<p>Also, before I discovered this logic, I've already implemented the following functions to redirect author links to the homepage, which gives em the same result:</p>
<pre><code># Redirect author page to homepage
add_action( 'template_redirect', 'author_page' );
function author_page() {
# If the author archive page is being accessed, redirect to homepage
if ( is_author() ) {
wp_safe_redirect( get_home_url(), 301 );
exit;
}
}
</code></pre>
<p>Is this function enough to prevent user enumeration? Or should I still apply one fo the following logics above?</p>
| [
{
"answer_id": 243018,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": true,
"text": "<p><strong>Logic #1</strong> is checking the returned value of the <code>preg_match</code> function with respe... | 2016/10/17 | [
"https://wordpress.stackexchange.com/questions/243012",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] | I'm disabling [user enumeration](https://hackertarget.com/wordpress-user-enumeration/) for security purposes in order to prevent usernames from being revealed by looking up the user IDs. Instead, whenever someone tried to find out the username by their ID, such as visiting the following:
```
http://example.com?author=1
```
It will redirect them to the homepage. After searching around, I've found two plugins which have this function, but both of them use slightly different logics to check if someone is trying to enumerate:
### Logic #1
```
if ( preg_match( '/(wp-comments-post)/', $_SERVER['REQUEST_URI'] ) === 0 && ! empty( $_REQUEST['author'] ) ) {
# Redirect to homepage...
}
```
### Logic #2
```
if ( ! preg_match( '/(wp-comments-post)/', $_SERVER['REQUEST_URI'] ) && ! empty( $_REQUEST['author'] ) && ( int ) $_REQUEST['author'] ) {
# Redirect to homepage...
}
```
Both logics work, but I'm wondering which one is more effective and what they are doing differently.
Also, before I discovered this logic, I've already implemented the following functions to redirect author links to the homepage, which gives em the same result:
```
# Redirect author page to homepage
add_action( 'template_redirect', 'author_page' );
function author_page() {
# If the author archive page is being accessed, redirect to homepage
if ( is_author() ) {
wp_safe_redirect( get_home_url(), 301 );
exit;
}
}
```
Is this function enough to prevent user enumeration? Or should I still apply one fo the following logics above? | **Logic #1** is checking the returned value of the `preg_match` function with respect to `0` and with operator `===`. That means the returned value of the `preg_match` function has to be `(int) 0` or `(string) 0`. And after that it is checking if `$_REQUEST['author']` is empty or not.
And in **Logic #2** is checking the same thing above, but with `!()`(not) operator. And this method also additionally check the `$_REQUEST['author']` is `integer` or not.
Checking the `$_REQUEST['author']` data type actually makes **Logic #2** better than above **Logic #1**, I think. Cause, though data type doesn't matter in `PHP` (`PHP` is a loosely typed language) but it's better to use them. It defines a concrete base for your application and ensures some core security as well as it's the best practice.
Hope that answer satisfies your quest. |
243,040 | <p>I've created a custom taxonomy for the product post type created by WooCommerce. I want to use this taxonomy to the permalinks of the products.</p>
<p>I stumbled upon <a href="https://wordpress.stackexchange.com/a/162670/2830">this</a> which seemed to be perfect for what I wanted to do.
However, I'm having little luck getting it to work. Adding the code in the post I still end up with %item% (which I'm using, rather than %artist%) rather than the term in my permalink.</p>
<pre><code><?php
/*
Plugin Name: Woocommerce Item Taxonomy
Description: Enables a Taxonomy called "Item" for organizing multiple single products under an unified item.
Version: 1.0.0
License: MIT License
*/
add_action( 'init', 'ps_taxonomy_item' );
function ps_taxonomy_item() {
$labels = array(
'name' => 'Item',
'singular_name' => 'Item',
'menu_name' => 'Item',
'all_items' => 'All Items',
'parent_item' => 'Parent Item',
'parent_item_colon' => 'Parent Item:',
'new_item_name' => 'New Item Name',
'add_new_item' => 'Add New Item',
'edit_item' => 'Edit Item',
'update_item' => 'Update Item',
'separate_items_with_commas' => 'Separate Item with commas',
'search_items' => 'Search Items',
'add_or_remove_items' => 'Add or remove Items',
'choose_from_most_used' => 'Choose from the most used Items',
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'item', 'product', $args );
register_taxonomy_for_object_type( 'item', 'product' );
}
/**
* replace the '%item%' tag with the first
* term slug in the item taxonomy
*
* @wp-hook post_link
* @param string $permalink
* @param WP_Post $post
* @return string
*/
add_filter( 'post_link', 'wpse_56769_post_link', 10, 2 );
function wpse_56769_post_link( $permalink, $post ) {
$default_term = 'no_item';
$terms = wp_get_post_terms( $post->ID, 'item' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) )
$term = current( $terms )->slug;
else
$term = $default_term;
$permalink = str_replace( '%item%', $term, $permalink );
return $permalink;
}
/**
* set WP_Rewrite::use_verbose_page_rules to TRUE if %item%
* is used as the first rewrite tag in post permalinks
*
* @wp-hook do_parse_request
* @wp-hook page_rewrite_rules
* @global $wp_rewrite
* @param mixed $pass_through (Unused)
* @return mixed
*/
function wpse_56769_rewrite_verbose_page_rules( $pass_through = NULL ) {
$permastruct = $GLOBALS[ 'wp_rewrite' ]->permalink_structure;
$permastruct = trim( $permastruct, '/%' );
if ( 0 !== strpos( $permastruct, 'item%' ) )
return $pass_through;
$GLOBALS[ 'wp_rewrite' ]->use_verbose_page_rules = TRUE;
return $pass_through;
}
add_filter( 'page_rewrite_rules', 'wpse_56769_rewrite_verbose_page_rules', PHP_INT_MAX );
add_filter( 'do_parse_request', 'wpse_56769_rewrite_verbose_page_rules', PHP_INT_MAX );
/**
* check for existing item and set query to 404 if necessary
*
* @wp-hook parse_query
* @param array $request_vars
* @return array
*/
function wpse_56769_request_vars( $request_vars ) {
if ( ! isset( $request_vars[ 'item' ] ) )
return $request_vars;
if ( ! isset( $request_vars[ 'name' ] ) )
return $request_vars;
if ( 'no_item' == $request_vars[ 'item' ] )
unset( $request_vars[ 'item' ] );
return $request_vars;
}
add_filter( 'request', 'wpse_56769_request_vars' );
</code></pre>
| [
{
"answer_id": 243041,
"author": "INT",
"author_id": 2830,
"author_profile": "https://wordpress.stackexchange.com/users/2830",
"pm_score": 3,
"selected": true,
"text": "<p>As always it was too simple in the end, was using the wrong hook. <code>post_link</code> is for posts only should us... | 2016/10/17 | [
"https://wordpress.stackexchange.com/questions/243040",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2830/"
] | I've created a custom taxonomy for the product post type created by WooCommerce. I want to use this taxonomy to the permalinks of the products.
I stumbled upon [this](https://wordpress.stackexchange.com/a/162670/2830) which seemed to be perfect for what I wanted to do.
However, I'm having little luck getting it to work. Adding the code in the post I still end up with %item% (which I'm using, rather than %artist%) rather than the term in my permalink.
```
<?php
/*
Plugin Name: Woocommerce Item Taxonomy
Description: Enables a Taxonomy called "Item" for organizing multiple single products under an unified item.
Version: 1.0.0
License: MIT License
*/
add_action( 'init', 'ps_taxonomy_item' );
function ps_taxonomy_item() {
$labels = array(
'name' => 'Item',
'singular_name' => 'Item',
'menu_name' => 'Item',
'all_items' => 'All Items',
'parent_item' => 'Parent Item',
'parent_item_colon' => 'Parent Item:',
'new_item_name' => 'New Item Name',
'add_new_item' => 'Add New Item',
'edit_item' => 'Edit Item',
'update_item' => 'Update Item',
'separate_items_with_commas' => 'Separate Item with commas',
'search_items' => 'Search Items',
'add_or_remove_items' => 'Add or remove Items',
'choose_from_most_used' => 'Choose from the most used Items',
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'item', 'product', $args );
register_taxonomy_for_object_type( 'item', 'product' );
}
/**
* replace the '%item%' tag with the first
* term slug in the item taxonomy
*
* @wp-hook post_link
* @param string $permalink
* @param WP_Post $post
* @return string
*/
add_filter( 'post_link', 'wpse_56769_post_link', 10, 2 );
function wpse_56769_post_link( $permalink, $post ) {
$default_term = 'no_item';
$terms = wp_get_post_terms( $post->ID, 'item' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) )
$term = current( $terms )->slug;
else
$term = $default_term;
$permalink = str_replace( '%item%', $term, $permalink );
return $permalink;
}
/**
* set WP_Rewrite::use_verbose_page_rules to TRUE if %item%
* is used as the first rewrite tag in post permalinks
*
* @wp-hook do_parse_request
* @wp-hook page_rewrite_rules
* @global $wp_rewrite
* @param mixed $pass_through (Unused)
* @return mixed
*/
function wpse_56769_rewrite_verbose_page_rules( $pass_through = NULL ) {
$permastruct = $GLOBALS[ 'wp_rewrite' ]->permalink_structure;
$permastruct = trim( $permastruct, '/%' );
if ( 0 !== strpos( $permastruct, 'item%' ) )
return $pass_through;
$GLOBALS[ 'wp_rewrite' ]->use_verbose_page_rules = TRUE;
return $pass_through;
}
add_filter( 'page_rewrite_rules', 'wpse_56769_rewrite_verbose_page_rules', PHP_INT_MAX );
add_filter( 'do_parse_request', 'wpse_56769_rewrite_verbose_page_rules', PHP_INT_MAX );
/**
* check for existing item and set query to 404 if necessary
*
* @wp-hook parse_query
* @param array $request_vars
* @return array
*/
function wpse_56769_request_vars( $request_vars ) {
if ( ! isset( $request_vars[ 'item' ] ) )
return $request_vars;
if ( ! isset( $request_vars[ 'name' ] ) )
return $request_vars;
if ( 'no_item' == $request_vars[ 'item' ] )
unset( $request_vars[ 'item' ] );
return $request_vars;
}
add_filter( 'request', 'wpse_56769_request_vars' );
``` | As always it was too simple in the end, was using the wrong hook. `post_link` is for posts only should use `post_type_link` instead.
```
/**
* replace the '%item%' tag with the first
* term slug in the item taxonomy
*
* @wp-hook post_link
* @param string $permalink
* @param WP_Post $post
* @return string
*/
add_filter( 'post_type_link', 'wpse_56769_post_link', 10, 2 );
function wpse_56769_post_link( $permalink, $post ) {
if( $post->post_type == 'product' ) {
$default_term = 'no_item';
$terms = wp_get_post_terms( $post->ID, 'item' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) )
$term = current( $terms )->slug;
else
$term = $default_term;
$permalink = str_replace( '%item%', $term, $permalink );
}
return $permalink;
}
``` |
243,043 | <p>I having an issue getting a variable to work for one of my arguments in a query. I am using a custom post type and category name as terms to determine which categories are displayed.</p>
<p>When I hardcode the values into the terms it works fine, but when I use a variable it doesn't seem to work.</p>
<p><strong>This code works:</strong></p>
<pre><code>$args = array(
'post_type' => 'sparknz',
'tax_query' => array(
array(
'taxonomy' => 'sparknz_gardens',
'field' => 'name',
'terms' => array ( 'The A Team', 'The B Team', 'The C Team' ),
)
)
);
</code></pre>
<p><strong>But this does not (notice variable in terms):</strong></p>
<pre><code>$my_term_names = "'The A Team','The B Team','The C Team'";
$args = array(
'post_type' => 'sparknz',
'tax_query' => array(
array(
'taxonomy' => 'sparknz_gardens',
'field' => 'name',
'terms' => array( $my_term_names ),
)
)
);
</code></pre>
<p>I need the terms to be a variable. Any Ideas?</p>
<p><strong>Just an update as to why I am using a string as a variable. I am using <code>array_intersect</code> to pick out similarities in two arrays:</strong></p>
<pre><code>$my_user_array = array( "c" => $user_array );
$my_cat_array = array( "d" => $category_array );
$myresult = array_intersect( $my_user_array, $my_cat_array );
$my_term_names = implode( ",", $myresult );
echo $$my_term_names;
</code></pre>
<p>Not sure if there is another way to do this?</p>
| [
{
"answer_id": 243048,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>just upload it through ftp or your domain hosting panel to your public_html (www) directory. It will be there... | 2016/10/17 | [
"https://wordpress.stackexchange.com/questions/243043",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105139/"
] | I having an issue getting a variable to work for one of my arguments in a query. I am using a custom post type and category name as terms to determine which categories are displayed.
When I hardcode the values into the terms it works fine, but when I use a variable it doesn't seem to work.
**This code works:**
```
$args = array(
'post_type' => 'sparknz',
'tax_query' => array(
array(
'taxonomy' => 'sparknz_gardens',
'field' => 'name',
'terms' => array ( 'The A Team', 'The B Team', 'The C Team' ),
)
)
);
```
**But this does not (notice variable in terms):**
```
$my_term_names = "'The A Team','The B Team','The C Team'";
$args = array(
'post_type' => 'sparknz',
'tax_query' => array(
array(
'taxonomy' => 'sparknz_gardens',
'field' => 'name',
'terms' => array( $my_term_names ),
)
)
);
```
I need the terms to be a variable. Any Ideas?
**Just an update as to why I am using a string as a variable. I am using `array_intersect` to pick out similarities in two arrays:**
```
$my_user_array = array( "c" => $user_array );
$my_cat_array = array( "d" => $category_array );
$myresult = array_intersect( $my_user_array, $my_cat_array );
$my_term_names = implode( ",", $myresult );
echo $$my_term_names;
```
Not sure if there is another way to do this? | just upload it through ftp or your domain hosting panel to your public\_html (www) directory. It will be there as a link to www.example.com/myfile.pdf.
The case may be that if you have wordpress and installed any security plugins you'll have to allow the exception within that plugin as well. |
243,070 | <p>Using the <a href="https://codex.wordpress.org/Function_Reference/remove_menu_page" rel="noreferrer"><code>remove_menu_page()</code></a> function works for removing the default admin menu items by their slug like so:</p>
<pre><code>add_action( 'admin_menu', 'hide_menu' );
function hide_menu() {
remove_menu_page( 'index.php' ); // Dashboard
remove_menu_page( 'tools.php' ); // Tools
}
</code></pre>
<p>When a plugin created their own menu in the Dashboard, the URL structure looks like the following:</p>
<pre><code>http://example.com/wp-admin/admin.php?page=plugin-slug
</code></pre>
<p>However when trying to remove the custom plugin menu item like so:</p>
<pre><code>remove_menu_page( 'admin.php?page=plugin-slug' );
</code></pre>
<p>Nothing changes. Looking at a similar questions <a href="https://wordpress.stackexchange.com/q/169934/98212">here</a> and <a href="https://wordpress.stackexchange.com/q/132210/98212">here</a>, it seems that my function isn't called in time once the custom plugin settings load? Yet, when I try to increase the priority to a higher number, that still doesn't work:</p>
<pre><code>add_action( 'admin_menu', 'hide_menu', 9001, 1 );
</code></pre>
<p>Is there a work around? Am I doing this correctly?</p>
| [
{
"answer_id": 243073,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 4,
"selected": false,
"text": "<p>Place this below temporary code in your <code>functions.php</code> or any where that can be executed.</p>\... | 2016/10/18 | [
"https://wordpress.stackexchange.com/questions/243070",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] | Using the [`remove_menu_page()`](https://codex.wordpress.org/Function_Reference/remove_menu_page) function works for removing the default admin menu items by their slug like so:
```
add_action( 'admin_menu', 'hide_menu' );
function hide_menu() {
remove_menu_page( 'index.php' ); // Dashboard
remove_menu_page( 'tools.php' ); // Tools
}
```
When a plugin created their own menu in the Dashboard, the URL structure looks like the following:
```
http://example.com/wp-admin/admin.php?page=plugin-slug
```
However when trying to remove the custom plugin menu item like so:
```
remove_menu_page( 'admin.php?page=plugin-slug' );
```
Nothing changes. Looking at a similar questions [here](https://wordpress.stackexchange.com/q/169934/98212) and [here](https://wordpress.stackexchange.com/q/132210/98212), it seems that my function isn't called in time once the custom plugin settings load? Yet, when I try to increase the priority to a higher number, that still doesn't work:
```
add_action( 'admin_menu', 'hide_menu', 9001, 1 );
```
Is there a work around? Am I doing this correctly? | Thanks to the answer that [the\_dramatist](https://wordpress.stackexchange.com/users/44192) posted, it was a matter of just hooking to the [`admin_init`](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init) tag. The slugs for those plugin pages can be retrieved by the debug script that the\_dramatist provided, or you can simply look at that query value after `admin.php?page=plugin-slug`:
```
add_action( 'admin_menu', 'wpse_243070_hide_menu' );
function wpse_243070_hide_menu() {
remove_menu_page( 'index.php' ); // Dashboard
remove_menu_page( 'tools.php' ); // Tools
remove_menu_page( 'plugin-slug' ); // Some plugin
remove_menu_page( 'another_slug' ); // Another plugin
}
``` |
243,168 | <p>I'm using ACF (Advance Custom Fields) plugin in my theme. This plugin provides a simpler methods <code>get_field()</code> which we can use in place of WordPress native <code>get_post_meta()</code> method. Now, the issue is the <code>get_field()</code> method works fine if ACF plugin is active, but when the plugin is not active the theme front-end throughs the following error:</p>
<p><code>Fatal error: Call to undefined function get_field()</code></p>
<p>Now, I tried to provide a fallback function, which should be used when the plugin is not active, my fallback function is below:</p>
<pre><code>if ( !function_exists('get_field') ) {
function get_field($key) {
return get_post_meta(get_the_ID(), $key, true);
}
}
add_action( 'after_setup_theme', 'get_field' );
</code></pre>
<p>Now, this function do work when the ACF plugin is not active but as soon as I try to activate the ACF plugin the backend throughs an error that:</p>
<p><code>Fatal error: Cannot redeclare get_field()</code></p>
<p>Now, I want to use my fallback function ONLY when plugin is not active and it shoud not stop activation of the ACF plugin afterwards. </p>
<p>What could be the solution?</p>
| [
{
"answer_id": 244263,
"author": "David",
"author_id": 12976,
"author_profile": "https://wordpress.stackexchange.com/users/12976",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow\">afte... | 2016/10/18 | [
"https://wordpress.stackexchange.com/questions/243168",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45269/"
] | I'm using ACF (Advance Custom Fields) plugin in my theme. This plugin provides a simpler methods `get_field()` which we can use in place of WordPress native `get_post_meta()` method. Now, the issue is the `get_field()` method works fine if ACF plugin is active, but when the plugin is not active the theme front-end throughs the following error:
`Fatal error: Call to undefined function get_field()`
Now, I tried to provide a fallback function, which should be used when the plugin is not active, my fallback function is below:
```
if ( !function_exists('get_field') ) {
function get_field($key) {
return get_post_meta(get_the_ID(), $key, true);
}
}
add_action( 'after_setup_theme', 'get_field' );
```
Now, this function do work when the ACF plugin is not active but as soon as I try to activate the ACF plugin the backend throughs an error that:
`Fatal error: Cannot redeclare get_field()`
Now, I want to use my fallback function ONLY when plugin is not active and it shoud not stop activation of the ACF plugin afterwards.
What could be the solution? | The issue has been solved. It seems ACF plugin defined `get_field()` function is not able to override the theme defined `get_field()` function on ACF plugin activation. Therefore, it throws `Fatal error: Cannot redeclare get_field(`) error if we use the following code:
```
if ( !function_exists('get_field') ) {
function get_field($key) {
return get_post_meta(get_the_ID(), $key, true);
}
}
```
Now since, before activating ACF plugin, we only need this custom wrapper function in front-end of our theme we can limit it's registration only to the front-end like this:
```
if ( !is_admin() && !function_exists('get_field') ) {
function get_field($key) {
return get_post_meta(get_the_ID(), $key, true);
}
}
```
Now, our backend is not aware of our custom defined `get_field()` function so it won't cause any issue while activating the plugin and after activating the plugin the ACF plugin's `get_field()` function will take over as expected. |
243,176 | <p>I know from <a href="https://wordpress.stackexchange.com/questions/180137/retrieving-pages-with-multiple-tags-using-rest-api">this post</a> that I can get posts by tag <em>name</em> by just specifying a <code>filter[tag]</code> query parameter. And similarly with <code>filter[category_name]</code>.</p>
<p>Is there a way to get posts that are <strong>not</strong> in a list of tags or categories for the purpose of excluding posts? I would prefer to do it with the name, or else I would have to make another request just to get the ID of the category, which would just slow down my overall response time in my app.</p>
| [
{
"answer_id": 244263,
"author": "David",
"author_id": 12976,
"author_profile": "https://wordpress.stackexchange.com/users/12976",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow\">afte... | 2016/10/18 | [
"https://wordpress.stackexchange.com/questions/243176",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102669/"
] | I know from [this post](https://wordpress.stackexchange.com/questions/180137/retrieving-pages-with-multiple-tags-using-rest-api) that I can get posts by tag *name* by just specifying a `filter[tag]` query parameter. And similarly with `filter[category_name]`.
Is there a way to get posts that are **not** in a list of tags or categories for the purpose of excluding posts? I would prefer to do it with the name, or else I would have to make another request just to get the ID of the category, which would just slow down my overall response time in my app. | The issue has been solved. It seems ACF plugin defined `get_field()` function is not able to override the theme defined `get_field()` function on ACF plugin activation. Therefore, it throws `Fatal error: Cannot redeclare get_field(`) error if we use the following code:
```
if ( !function_exists('get_field') ) {
function get_field($key) {
return get_post_meta(get_the_ID(), $key, true);
}
}
```
Now since, before activating ACF plugin, we only need this custom wrapper function in front-end of our theme we can limit it's registration only to the front-end like this:
```
if ( !is_admin() && !function_exists('get_field') ) {
function get_field($key) {
return get_post_meta(get_the_ID(), $key, true);
}
}
```
Now, our backend is not aware of our custom defined `get_field()` function so it won't cause any issue while activating the plugin and after activating the plugin the ACF plugin's `get_field()` function will take over as expected. |
243,178 | <p>I am using hard-crop on featured images like this :</p>
<pre><code>add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size ( 635, 200, true );
</code></pre>
<p>I have no other plugin installed, not even Jetpack.
No matter how large the image I upload wordpress won't add srcset for my cropped featured images.</p>
<p><strong><em>EDIT</em></strong>: The problem seems to be with hard crop feature because the srcset shows correctly on any other image posted in article (from media for example). If I deactivate the hard crop the srcset shows correctly on the thumbnails too.</p>
| [
{
"answer_id": 243284,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 4,
"selected": true,
"text": "<p>To show a srcset, there must be multiple image sizes of the same aspect ratio. When you set your t... | 2016/10/18 | [
"https://wordpress.stackexchange.com/questions/243178",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104433/"
] | I am using hard-crop on featured images like this :
```
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size ( 635, 200, true );
```
I have no other plugin installed, not even Jetpack.
No matter how large the image I upload wordpress won't add srcset for my cropped featured images.
***EDIT***: The problem seems to be with hard crop feature because the srcset shows correctly on any other image posted in article (from media for example). If I deactivate the hard crop the srcset shows correctly on the thumbnails too. | To show a srcset, there must be multiple image sizes of the same aspect ratio. When you set your thumbnail to hard crop without creating any other image sizes you are ensuring that there won't be a srcset.
You might find my answer [here](https://wordpress.stackexchange.com/a/241906/94267) helpful.
Briefly, in your case, adding this line:
```
add_image_size ( 'double-size', 1270, 400, true );
```
... will make a srcset with both the cropped sizes when you upload a fresh image larger than 1270x400. |
243,209 | <p>My client has dragged around the sub-categories in the admin panel to change their order. </p>
<p>I have the following code that outputs the sub-categories of a specific category parent:</p>
<pre><code>$mainCategory = get_categories(
array (
'parent' => $category_id['term_id'],
'taxonomy' => 'product_cat',
'orderby' => 'menu_order'
)
);
foreach( $mainCategory as $mc ) {
$cat_link = get_category_link( $mc->term_id );
echo '<div class="main-category col-md-3">';
echo '<a href="'.$cat_link.'">';
$thumbnail_id = get_woocommerce_term_meta( $mc->term_id, 'thumbnail_id', true ); // Get Category Thumbnail
$image = wp_get_attachment_url( $thumbnail_id );
if ( $image ) {
echo '<div class="mc-img">';
echo '<img src="' . $image . '" alt="" />';
echo '</div>';
}
echo '<h2>';
echo $mc->name;
echo '</h2>';
echo '<p>';
echo $mc->description;
echo '</p>';
echo '<div class="mc-button">Explore Products</div>';
echo '</a>';
echo '</div>';
}
</code></pre>
<p>The categories are output in alphabetical order, rather than the order specified by the admin in the dashboard.</p>
<p>'menu_order' does not work</p>
| [
{
"answer_id": 243225,
"author": "Aurovrata",
"author_id": 52120,
"author_profile": "https://wordpress.stackexchange.com/users/52120",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you use the <a href=\"https://codex.wordpress.org/Navigation_Menus\" rel=\"nofollow\">Navigationa... | 2016/10/19 | [
"https://wordpress.stackexchange.com/questions/243209",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31560/"
] | My client has dragged around the sub-categories in the admin panel to change their order.
I have the following code that outputs the sub-categories of a specific category parent:
```
$mainCategory = get_categories(
array (
'parent' => $category_id['term_id'],
'taxonomy' => 'product_cat',
'orderby' => 'menu_order'
)
);
foreach( $mainCategory as $mc ) {
$cat_link = get_category_link( $mc->term_id );
echo '<div class="main-category col-md-3">';
echo '<a href="'.$cat_link.'">';
$thumbnail_id = get_woocommerce_term_meta( $mc->term_id, 'thumbnail_id', true ); // Get Category Thumbnail
$image = wp_get_attachment_url( $thumbnail_id );
if ( $image ) {
echo '<div class="mc-img">';
echo '<img src="' . $image . '" alt="" />';
echo '</div>';
}
echo '<h2>';
echo $mc->name;
echo '</h2>';
echo '<p>';
echo $mc->description;
echo '</p>';
echo '<div class="mc-button">Explore Products</div>';
echo '</a>';
echo '</div>';
}
```
The categories are output in alphabetical order, rather than the order specified by the admin in the dashboard.
'menu\_order' does not work | Answering for posterity, since I ran into the same issue and this thread is the closest thing I found to what I was looking for.
The solution turned out to be quite simple.
If you don't specify 'orderby' in your arguments, the default sort order will be used (the category order in the Woo admin). Just remove that part of your arguments. |
243,233 | <p>I know it has been asked many times on this website but I can't really get it to work with those examples. </p>
<p>This is my function so far:</p>
<pre><code>$city_ids = get_pages(
array(
"hierarchical" => 0,
"sort_column" => "menu_order",
"sort_order" => "desc",
"meta_key" => "country",
"meta_value" => $atts['country']
)
);
</code></pre>
<p>This works. It gives me the page I want (Verhuizen naar Nederland), but I now need to child pages. It has three pages. See (There is one more):</p>
<p><a href="https://i.stack.imgur.com/Q1H90.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q1H90.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 243225,
"author": "Aurovrata",
"author_id": 52120,
"author_profile": "https://wordpress.stackexchange.com/users/52120",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you use the <a href=\"https://codex.wordpress.org/Navigation_Menus\" rel=\"nofollow\">Navigationa... | 2016/10/19 | [
"https://wordpress.stackexchange.com/questions/243233",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104179/"
] | I know it has been asked many times on this website but I can't really get it to work with those examples.
This is my function so far:
```
$city_ids = get_pages(
array(
"hierarchical" => 0,
"sort_column" => "menu_order",
"sort_order" => "desc",
"meta_key" => "country",
"meta_value" => $atts['country']
)
);
```
This works. It gives me the page I want (Verhuizen naar Nederland), but I now need to child pages. It has three pages. See (There is one more):
[](https://i.stack.imgur.com/Q1H90.png) | Answering for posterity, since I ran into the same issue and this thread is the closest thing I found to what I was looking for.
The solution turned out to be quite simple.
If you don't specify 'orderby' in your arguments, the default sort order will be used (the category order in the Woo admin). Just remove that part of your arguments. |
243,238 | <p>I created new custom field within my nav menu items as multiple select options i used <code>update_post_meta()</code> as below</p>
<pre><code>function YPE_update_custom_fields($menu_id, $menu_item_db_id, $menu_item_data) {
if (is_array($_REQUEST['menu-item-content-multiple'])) {
update_post_meta($menu_item_db_id, '_menu_item_content_multiple', $_REQUEST['menu-item-content-multiple'][$menu_item_db_id]);
}
}
add_action('wp_update_nav_menu_item', 'YPE_update_custom_fields', 10, 3);
function YPE_setup_custom_fields($item) {
$item->content_multiple = get_post_meta($item->ID, '_menu_item_content_multiple', true);
return $item;
}
add_filter('wp_setup_nav_menu_item', 'YPE_setup_custom_fields');
</code></pre>
<p>Then I add new field into <code>Walker_Nav_Menu_Edit</code> file as below</p>
<p><strong>EDITED</strong> </p>
<pre><code><?php
$select_options = array (
'key_1' => 'option1',
'key_2' => 'option2',
'key_3' => 'option3'
);
?>
<p class="field-content-multiple description description-thin">
<label for="edit-menu-item-content-multiple-<?php echo $item_id; ?>">
<?php _e( 'Multiple Content' ); ?><br />
<select name="menu-item-content-multiple[<?php echo $item_id; ?>][]" id="edit-menu-item-content-multiple-<?php echo $item_id; ?>" class="widefat code edit-menu-item-content-multiple" multiple="multiple">
<?php foreach ($select_options as $key => $value): ?>
<option value="<?php echo $key; ?>" <?php echo selected(in_array($key, $item->content_multiple)); ?>><?php echo $value;?></option>
<?php endforeach ?>
</select>
</label>
</p>
</code></pre>
<p>My code is work with the single select box without any problem but when I use <code>in_array()</code> in multiple select cases return this error</p>
<pre><code>Warning: in_array() expects parameter 2 to be array, null given
</code></pre>
| [
{
"answer_id": 243241,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>You don't use <code>selected()</code> function correctly. <code>selected()</code> need 1 required parameters a... | 2016/10/19 | [
"https://wordpress.stackexchange.com/questions/243238",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37216/"
] | I created new custom field within my nav menu items as multiple select options i used `update_post_meta()` as below
```
function YPE_update_custom_fields($menu_id, $menu_item_db_id, $menu_item_data) {
if (is_array($_REQUEST['menu-item-content-multiple'])) {
update_post_meta($menu_item_db_id, '_menu_item_content_multiple', $_REQUEST['menu-item-content-multiple'][$menu_item_db_id]);
}
}
add_action('wp_update_nav_menu_item', 'YPE_update_custom_fields', 10, 3);
function YPE_setup_custom_fields($item) {
$item->content_multiple = get_post_meta($item->ID, '_menu_item_content_multiple', true);
return $item;
}
add_filter('wp_setup_nav_menu_item', 'YPE_setup_custom_fields');
```
Then I add new field into `Walker_Nav_Menu_Edit` file as below
**EDITED**
```
<?php
$select_options = array (
'key_1' => 'option1',
'key_2' => 'option2',
'key_3' => 'option3'
);
?>
<p class="field-content-multiple description description-thin">
<label for="edit-menu-item-content-multiple-<?php echo $item_id; ?>">
<?php _e( 'Multiple Content' ); ?><br />
<select name="menu-item-content-multiple[<?php echo $item_id; ?>][]" id="edit-menu-item-content-multiple-<?php echo $item_id; ?>" class="widefat code edit-menu-item-content-multiple" multiple="multiple">
<?php foreach ($select_options as $key => $value): ?>
<option value="<?php echo $key; ?>" <?php echo selected(in_array($key, $item->content_multiple)); ?>><?php echo $value;?></option>
<?php endforeach ?>
</select>
</label>
</p>
```
My code is work with the single select box without any problem but when I use `in_array()` in multiple select cases return this error
```
Warning: in_array() expects parameter 2 to be array, null given
``` | You do this:
```
$item->content_multiple = get_post_meta($item->ID, '_menu_item_content_multiple', true);
```
Note how you set the third parameter of `get_post_meta()` to `true`, which means that only one value will be returned. [If you read the docs](https://developer.wordpress.org/reference/functions/get_post_meta/), you will see that, if the third parameter is `false`, you will get an **array** with all the values for that meta field.
Remember that meta fields can be unique or can be multiple. Or it can be unique with a serialized data string.
As it is, your code seems to store all values from the select multiple into one single meta field. So, you get an array in the request and pass it as single value of the meta field. When the value of a meta field is an array, WordPress **converts it to a serialized string before it is stored in the database**; this is done internally with the function `maybe_serialize()`. Then, when you try to get the value of the meta field, if it is a serialized string, WordPress pass it through `maybe_unserialize()`, so the serialized string converts back to the array:
Let's explain with a generic example.
This will be the array of values to be stored in the database:
```
$values = [ 'red', 'yellow', 'blue', 'pink' ];
```
If your meta key is "color", the you have two options:
Multiple entries for the same meta key
--------------------------------------
```
$values = [ 'red', 'yellow', 'blue', 'pink' ];
foreach( $values as $value ) {
// This method uses `add_post_meta()` instead of `update_post_meta()`
add_post_meta( $item_id, 'color', $value );
}
```
Now, the item identified with `$item_id` will have several entries for the `color` meta key. Then, you can use `get_post_meta()` with the third parameter set to `false` and you will get an array with all the values:
```
// You don't really need the set the third parameter
// because it is false vay default
$colors = get_post_meta( $item_id, 'color' );
// $colors should an array with all the meta values for the color meta key
var_dump( $colors );
```
Store the array in a single meta entry
--------------------------------------
In this case, the array of values is serialized before it is sotred in database:
```
$values = [ 'red', 'yellow', 'blue', 'pink' ];
// WordPress does this automatically when an array is passed as meta value
// $values = maybe_serialize( $values );
update_post_meta( $item_id, 'color', $values );
```
Now, the item identified with `$item_id` will have only one entry for the `color` meta key; the value is a serialized string representing the original array. Then, you can use `get_post_meta()`, with the third parameter set to true, as you have only one entry, and then unserialize the string to get back the array:
```
$colors = get_post_meta( $item_id, 'color', true );
// WordPress does this automatically when the meta value is a serialized array
// $colors = maybe_unserialize( $colors );
// $colors should be an array
var_dump( $colors );
```
You can follow the same approach with the select multiple of your form.
**With only one entry for the meta key:**
```
if( ! empty( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) ) {
$meta_field_value = $_REQUEST['menu-item-content-multiple'][$menu_item_db_id];
// $meta_field_value will be serialized automatically by WordPress
update_post_meta( $menu_item_db_id, '_menu_item_content_multiple', $meta_field_value );
}
```
Then, you can use the value as array:
```
// The value returned by get_post_meta() is unserialized automatically by WordPress
$item->content_multiple = get_post_meta( $item->ID, '_menu_item_content_multiple', true );
```
**With multiple entries:**
The concept here is a bit different; you will several entries in the database with the same meta key, so you need to use `add_post_meta()` instead of `update_post_meta()` in order to add a new entry for each value.
```
if( ! empty( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) ) {
$values = $_REQUEST[ 'menu-item-content-multiple' . $menu_item_db_id ];
foreach( $values as $value ) {
add_post_meta( $menu_item_db_id, '_menu_item_content_multiple', $value );
}
}
```
Now, you can use `get_post_meta()` with the third parameter set to `false` (it is the default value, so you can omit it):
```
$item->content_multiple = get_post_meta( $item->ID, '_menu_item_content_multiple', false );
```
Both options are OK, you must decide which one is better to organize the data within your project.
**Side note**: you should do some santization before using the input data, but I don't know the requirements for you, here a example:
```
array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) );
``` |
243,245 | <p>I'm trying to figure out how to redeclare a theme's function from within a plugin. The problem is that I'm getting a "Fatal error: Cannot redeclare" when trying to activate the plugin. But if I add the code to already activated plugin - everything is working as expected. Is there something obvious that I'm missing? </p>
<p>Here's a simplified example of the code I'm using:</p>
<pre><code>// In my theme I use function_exists check
if ( ! function_exists( 'my_awesome_function' ) ) {
function my_awesome_function() {
return "theme";
}
}
// Now I want to override 'my_awesome_function' output in a plugin
function my_awesome_function() {
return "plugin";
}
</code></pre>
<p>EDIT:</p>
<p>In the given example I need <code>my_awesome_function()</code> to return <code>plugin</code> if the plugin is active and <code>theme</code> otherwise. So I need to keep the original function in the theme.</p>
<p>Basically, I thought that if such approach works for child themes, it should work for plugins too. But obviously, I was wrong.</p>
| [
{
"answer_id": 243247,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>You can only declare a function once.</p>\n\n<p>My reccomendation is that you put the functions in the plugi... | 2016/10/19 | [
"https://wordpress.stackexchange.com/questions/243245",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31277/"
] | I'm trying to figure out how to redeclare a theme's function from within a plugin. The problem is that I'm getting a "Fatal error: Cannot redeclare" when trying to activate the plugin. But if I add the code to already activated plugin - everything is working as expected. Is there something obvious that I'm missing?
Here's a simplified example of the code I'm using:
```
// In my theme I use function_exists check
if ( ! function_exists( 'my_awesome_function' ) ) {
function my_awesome_function() {
return "theme";
}
}
// Now I want to override 'my_awesome_function' output in a plugin
function my_awesome_function() {
return "plugin";
}
```
EDIT:
In the given example I need `my_awesome_function()` to return `plugin` if the plugin is active and `theme` otherwise. So I need to keep the original function in the theme.
Basically, I thought that if such approach works for child themes, it should work for plugins too. But obviously, I was wrong. | You can only declare a function once.
My reccomendation is that you put the functions in the plugin, then use filters to override in the theme, e.g.
In the plugins:
```
function my_awesome_function() {
return apply_filters( 'my_awesome_function', "plugin" );
}
```
In your theme:
```
add_filter( 'my_awesome_function', function( $value ) {
return "theme";
} );
```
Now every call to `my_awesome_function();` will return "theme" not "plugin" |
243,276 | <p>I'd like to get post data from a private page to show on the rest of the site. The code looks like this:</p>
<pre><code>$the_query = new WP_Query( 'page_id=1457' );
while($the_query -> have_posts()) : $the_query -> the_post();
setup_postdata( $the_query );
// do something;
endwhile;
</code></pre>
<p>But I don't get the data.</p>
<p>Is it because I'm calling the data from a public site that is hidden on a private site?</p>
| [
{
"answer_id": 243277,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 0,
"selected": false,
"text": "<p>You don't need a query for this - in fact, that's part of the problem (WordPress will automatically \"filt... | 2016/10/19 | [
"https://wordpress.stackexchange.com/questions/243276",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105264/"
] | I'd like to get post data from a private page to show on the rest of the site. The code looks like this:
```
$the_query = new WP_Query( 'page_id=1457' );
while($the_query -> have_posts()) : $the_query -> the_post();
setup_postdata( $the_query );
// do something;
endwhile;
```
But I don't get the data.
Is it because I'm calling the data from a public site that is hidden on a private site? | `setup_postdata` takes a post object of type `\WP_Post`, but you're passing it a `WP_Query` instead
e.g.
```
global $post;
setup_postdata( $post );
```
Thankfully the solution is trivial, when you call `the_post`, it sets up the current post data for you, so removing that line is all you need to do.
The second issue is that `WP_Query` will filter out private posts if you're not logged in, so setting the post status to private is necessary.
An important thing you're missing though is the clean up call. You need to call `wp_reset_postdata()` when you're done so that code that runs after your loop has the current post and not the last post in your query.
Here's what that query might look like:
```
$the_query = new WP_Query( array(
'id' => '1457'
'post_type' => 'page',
'post_status' => 'private'
) );
if ( $the_query->have_posts() ) {
while( $the_query->have_posts() ) {
$the_query->the_post();
// do something;
}
wp_reset_postdata();
}
```
There's a faster way though, you already know the post ID, so we can do this:
```
$p = get_post( 1457 );
if ( null !== $p ) {
setup_postdata( $p );
// do things
wp_reset_postdata();
}
``` |
243,322 | <p>I want to increase the width of the expanded sidebar in the WP customizer. </p>
<p>The relevant customizer markup:</p>
<pre><code><div class="wp-full-overlay expanded preview-desktop">
<form id="customize-controls" class="wrap wp-full-overlay-sidebar">
<div id="customize-preview" class="wp-full-overlay-main">
</code></pre>
<p>The CSS:</p>
<pre><code>.wp-full-overlay.expanded {
margin-left: 300px;
}
.wp-full-overlay-sidebar {
width: 300px;
}
.wp-full-overlay-main {
right: auto;
width: 100%;
</code></pre>
<p>I tried it with this CSS in my childtheme´s style.css</p>
<pre><code>.wp-full-overlay.expanded {
margin-left: 500px !important;
}
#customize-controls.wp-full-overlay-sidebar {
width: 500px !important;
}
</code></pre>
<p>and these lines of JS in an enqueued scripts.js</p>
<pre><code>jQuery(document).ready(function( $ ) {
$(".wp-full-overlay.expanded").css("marginLeft", "500px");
$(".wp-full-overlay-sidebar").css("width", "500px");
});
</code></pre>
<p>but it does not work. </p>
| [
{
"answer_id": 243400,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": true,
"text": "<p>Enqueue a style sheet to your admin or dashboard with <code>admin_enqueue_scripts</code> hook like below-</... | 2016/10/19 | [
"https://wordpress.stackexchange.com/questions/243322",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89739/"
] | I want to increase the width of the expanded sidebar in the WP customizer.
The relevant customizer markup:
```
<div class="wp-full-overlay expanded preview-desktop">
<form id="customize-controls" class="wrap wp-full-overlay-sidebar">
<div id="customize-preview" class="wp-full-overlay-main">
```
The CSS:
```
.wp-full-overlay.expanded {
margin-left: 300px;
}
.wp-full-overlay-sidebar {
width: 300px;
}
.wp-full-overlay-main {
right: auto;
width: 100%;
```
I tried it with this CSS in my childtheme´s style.css
```
.wp-full-overlay.expanded {
margin-left: 500px !important;
}
#customize-controls.wp-full-overlay-sidebar {
width: 500px !important;
}
```
and these lines of JS in an enqueued scripts.js
```
jQuery(document).ready(function( $ ) {
$(".wp-full-overlay.expanded").css("marginLeft", "500px");
$(".wp-full-overlay-sidebar").css("width", "500px");
});
```
but it does not work. | Enqueue a style sheet to your admin or dashboard with `admin_enqueue_scripts` hook like below-
```
add_action( 'admin_enqueue_scripts', 'the_dramatist_admin_styles' );
function the_dramatist_admin_styles() {
wp_enqueue_style( 'admin-css-override', get_template_directory_uri() . '/your-admin-css-file.css', false );
}
```
And put your admin `css` code there. As your code above the inside of `your-admin-css-file.css` will look kinda like-
```
.wp-full-overlay.expanded {
margin-left: 500px !important;
}
#customize-controls.wp-full-overlay-sidebar {
width: 500px !important;
}
```
And it'll work. |
243,334 | <p>I am new with Wordpress,
I want to hide a custom fields from particular post types and the problem is the custom fields are same for other post types, if I remove the custom fields it will also remove from all post types and I want to hide custom fields for only specific post types.</p>
<p>For example the post types are:</p>
<blockquote>
<p>1.Package</p>
<p>2.Group tour </p>
<p>3.Excursion</p>
</blockquote>
<p>and custom fields are </p>
<blockquote>
<p>general info, price info,image,tab 1,tab2, activate itinerary
tab.itineary,tab3,activate price tab,price info,include,not
included..etc</p>
</blockquote>
<p>from post type excursion I want to hide (included and not included).</p>
<p>please help me to achieve this ???</p>
| [
{
"answer_id": 243347,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 1,
"selected": false,
"text": "<p>This should do it. Tested locally and it works.</p>\n\n<pre><code>// Hide 'included' and 'not included' custom ... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243334",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105184/"
] | I am new with Wordpress,
I want to hide a custom fields from particular post types and the problem is the custom fields are same for other post types, if I remove the custom fields it will also remove from all post types and I want to hide custom fields for only specific post types.
For example the post types are:
>
> 1.Package
>
>
> 2.Group tour
>
>
> 3.Excursion
>
>
>
and custom fields are
>
> general info, price info,image,tab 1,tab2, activate itinerary
> tab.itineary,tab3,activate price tab,price info,include,not
> included..etc
>
>
>
from post type excursion I want to hide (included and not included).
please help me to achieve this ??? | This should do it. Tested locally and it works.
```
// Hide 'included' and 'not included' custom meta fields
// from the edit 'excursion' post type page.
function my_exclude_custom_fields( $protected, $meta_key ) {
if ( 'excursion' == get_post_type() ) {
if ( in_array( $meta_key, array( 'included', 'not included' ) ) ) {
return true;
}
}
return $protected;
}
add_filter( 'is_protected_meta', 'my_exclude_custom_fields', 10, 2 );
``` |
243,345 | <p>I would like to know is there a hook in wordpress to edit prefix and postfix of the_title in wordpress.</p>
<p>The code in content.php</p>
<pre><code>the_title( '<h1 class="entry-title">', '</h1>' );
</code></pre>
<p>I would like to add content after the closing tag of h1.</p>
<p>When I use the_title hook the content is added inside the h1 tag.</p>
<p>Like to know how to add outside the h1 tag by using action hook (fron the plugin).</p>
| [
{
"answer_id": 243355,
"author": "startToday",
"author_id": 104608,
"author_profile": "https://wordpress.stackexchange.com/users/104608",
"pm_score": 0,
"selected": false,
"text": "<p>Using get_the_title() will work for you:</p>\n\n<pre><code><h1><?php echo get_the_title(); ?>... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243345",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105312/"
] | I would like to know is there a hook in wordpress to edit prefix and postfix of the\_title in wordpress.
The code in content.php
```
the_title( '<h1 class="entry-title">', '</h1>' );
```
I would like to add content after the closing tag of h1.
When I use the\_title hook the content is added inside the h1 tag.
Like to know how to add outside the h1 tag by using action hook (fron the plugin). | You can use it that way :
```
function add_suffix_to_title($title, $id = null){
if (! is_admin()) {
return '<h1>'.$title.'</h1> Your Suffix';
}
return $title;
}
add_action( 'the_title', 'add_suffix_to_title', 10, 1 );
```
And when you invoke the "the\_title" function remove the h1 tag :
```
the_title();
```
I hope that would help you. |
243,365 | <p>I've added a simple shortcode into my <code>functions.php</code> file which results in creating an Bootstrap Collapse into post. But when I try using that shortcode the accordion structure is not as supposed. Here's my code in <code>functions.php</code> file:</p>
<pre><code>function sth_collapse($atts, $content = null) {
$atts = shortcode_atts(array(
'title' => 'Click Me',
),
$atts,
'collapse'
);
$coll = '<div class="collapse-container">';
$coll .= '<a href="#collapse-content" data-toggle="collapse" class="collapse-header">' . $atts['title'] . '</a>';
$coll .= '<div id="collapse-content" class="collapse">' . $content . '</div>';
$coll .= '</div>';
return $coll;
}
add_shortcode('collapse', 'sth_collapse');
</code></pre>
<p>When I put that in test using <code>[collapse title="show"]test test[/collapse]</code> s shortcode generates this weird HTML structure:</p>
<pre><code><div class="collapse-container">
<a class="collapse-header collapsed" data-toggle="collapse" href="#collapse-content" aria-expanded="false">Show</a>
<div id="collapse-content" class="collapse" aria-expanded="false" style="height: 0px;"></div>
</div>
<br>
test test
<br>
<div class="collapse-container">
<a class="collapse-header collapsed" data-toggle="collapse" href="#collapse-content" aria-expanded="false">Click Me</a>
<div id="collapse-content" class="collapse"></div>
</div>
</code></pre>
<p>Did you notice how everything is duplicated ? 2 <code>.collapse-container</code>, 2 <code>collapse-header</code>, etc. Also for first <code>.collapse-header</code> title att defined in shortcode appears and for the second one the default title att. Also <code>$content</code> appears in wrong position, it shows all the time and clicking <code>a</code> doesn't trigger collapsing behavior. So I can say almost nothing worked fine, as I expect.
I looked at my <code>add_shortcode</code> callback function codes several times but I couldn't figure out what's wrong with that. Could you please help me on this ?</p>
| [
{
"answer_id": 243383,
"author": "M-R",
"author_id": 17061,
"author_profile": "https://wordpress.stackexchange.com/users/17061",
"pm_score": 3,
"selected": true,
"text": "<p>Make sure, your closing [collapse] does not miss \"/\" or is not converting to \"[collapse/]\".</p>\n"
},
{
... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243365",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104608/"
] | I've added a simple shortcode into my `functions.php` file which results in creating an Bootstrap Collapse into post. But when I try using that shortcode the accordion structure is not as supposed. Here's my code in `functions.php` file:
```
function sth_collapse($atts, $content = null) {
$atts = shortcode_atts(array(
'title' => 'Click Me',
),
$atts,
'collapse'
);
$coll = '<div class="collapse-container">';
$coll .= '<a href="#collapse-content" data-toggle="collapse" class="collapse-header">' . $atts['title'] . '</a>';
$coll .= '<div id="collapse-content" class="collapse">' . $content . '</div>';
$coll .= '</div>';
return $coll;
}
add_shortcode('collapse', 'sth_collapse');
```
When I put that in test using `[collapse title="show"]test test[/collapse]` s shortcode generates this weird HTML structure:
```
<div class="collapse-container">
<a class="collapse-header collapsed" data-toggle="collapse" href="#collapse-content" aria-expanded="false">Show</a>
<div id="collapse-content" class="collapse" aria-expanded="false" style="height: 0px;"></div>
</div>
<br>
test test
<br>
<div class="collapse-container">
<a class="collapse-header collapsed" data-toggle="collapse" href="#collapse-content" aria-expanded="false">Click Me</a>
<div id="collapse-content" class="collapse"></div>
</div>
```
Did you notice how everything is duplicated ? 2 `.collapse-container`, 2 `collapse-header`, etc. Also for first `.collapse-header` title att defined in shortcode appears and for the second one the default title att. Also `$content` appears in wrong position, it shows all the time and clicking `a` doesn't trigger collapsing behavior. So I can say almost nothing worked fine, as I expect.
I looked at my `add_shortcode` callback function codes several times but I couldn't figure out what's wrong with that. Could you please help me on this ? | Make sure, your closing [collapse] does not miss "/" or is not converting to "[collapse/]". |
243,373 | <p>Sorry if this is a duplicate – I can't find an answer.</p>
<p>How do I rewrite a custom post type archive page to a 'man-made' WordPress page?</p>
<p>For example:</p>
<ul>
<li>Single page: <code>http://www.mywebsite.com/cool-post-type/awesome-single-post/</code></li>
<li>Archive page: <code>http://www.mywebsite.com/cool-post-type/</code></li>
</ul>
<p>I want <code>http://www.mywebsite.com/cool-post-type/</code> to rewrite to <code>http://www.mywebsite.com/about-cool-post-types/</code>.</p>
<p>Can I just do this with htaccess and what would the syntax be? (I'm not good at htaccess!)</p>
<p>This does not work:</p>
<pre><code>RewriteRule ^cool-post-type\/\?$ /about-cool-post-types [L]
</code></pre>
<p>Or do I have to do this in the WordPress source code? I don't want to!</p>
| [
{
"answer_id": 243376,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 5,
"selected": true,
"text": "<p>This one's actually pretty easy. When you declare your post type using <a href=\"https://developer.wordpress.... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243373",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105331/"
] | Sorry if this is a duplicate – I can't find an answer.
How do I rewrite a custom post type archive page to a 'man-made' WordPress page?
For example:
* Single page: `http://www.mywebsite.com/cool-post-type/awesome-single-post/`
* Archive page: `http://www.mywebsite.com/cool-post-type/`
I want `http://www.mywebsite.com/cool-post-type/` to rewrite to `http://www.mywebsite.com/about-cool-post-types/`.
Can I just do this with htaccess and what would the syntax be? (I'm not good at htaccess!)
This does not work:
```
RewriteRule ^cool-post-type\/\?$ /about-cool-post-types [L]
```
Or do I have to do this in the WordPress source code? I don't want to! | This one's actually pretty easy. When you declare your post type using [register\_post\_type](https://developer.wordpress.org/reference/functions/register_post_type/), you need to add a new argument for 'has\_archive'.
So you'll add in something to the effect of:
```
'has_archive' => 'about-cool-post-types'
```
Then, go to your Settings > Permalinks to flush them and it should work. I tested it locally, and this seems to be the way to automatically generate your archive page at a different URL. Then, you should be able to create a page at the CPT's slug. |
243,377 | <p>I trying to program the following rules:</p>
<ol>
<li>When attachment uploaded on wp-admin/post.php page, on the act of uploading, rename it to <code>{post-slug}-{n}-[WxH].{ext}</code></li>
<li>When attachment uploaded on wp-admin/upload.php page, on the act of uploading, rename it to <code>{site-name}-{n}-[WxH].{ext}</code></li>
</ol>
<p>Where <code>{n}</code> is the numerical order, <code>[WxH]</code> the sizes applied by WordPress and <code>{ext}</code> its extension.</p>
<p>Item 1 I got with <code>add_attachment</code> hook. How can I achieve item 2? How to change the name of a file uploaded on Media Page on the act of uploading?</p>
| [
{
"answer_id": 243385,
"author": "Niels van Renselaar",
"author_id": 67313,
"author_profile": "https://wordpress.stackexchange.com/users/67313",
"pm_score": 0,
"selected": false,
"text": "<p>I suppose you could change the filename trough <a href=\"https://codex.wordpress.org/Plugin_API/F... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243377",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35834/"
] | I trying to program the following rules:
1. When attachment uploaded on wp-admin/post.php page, on the act of uploading, rename it to `{post-slug}-{n}-[WxH].{ext}`
2. When attachment uploaded on wp-admin/upload.php page, on the act of uploading, rename it to `{site-name}-{n}-[WxH].{ext}`
Where `{n}` is the numerical order, `[WxH]` the sizes applied by WordPress and `{ext}` its extension.
Item 1 I got with `add_attachment` hook. How can I achieve item 2? How to change the name of a file uploaded on Media Page on the act of uploading? | The best way of doing this might be to attach a custom field to each post to keep the increment {n}.
Something to the effect of:
```
$attach_inc = 1;
if ( is_single() ) {
if ( $attach_inc = get_post_meta( $post_id, 'attachment_inc', true ) ) {
$attach_inc++;
update_post_meta( $post_id, 'attachment_inc', $attach_inc );
} else {
add_post_meta( $post_id, 'attachment_inc', $attach_inc );
}
} else {
if ( $attach_inc = get_option( 'attachment_inc' ) ) {
$attach_inc++;
set_option( 'attachment_inc', $attach_inc );
} else {
add_option( 'attachment_inc', $attach_inc );
}
}
// DO YOUR ADD ATTACHMENT STUFF HERE
``` |
243,384 | <p>I want to dequeue all styles and scripts that are loaded on the front-end (EG. not the admin panel) by default.</p>
<p>I found this <a href="https://codex.wordpress.org/Function_Reference/wp_dequeue_script" rel="nofollow">function</a>, but am not sure how to utilize it to accomplish my goal.</p>
<p>I'm seeing a ton of assets that I don't need on the front end, loaded by WP core:</p>
<p>For example:</p>
<ol>
<li>backbone.js</li>
<li>jquery UI</li>
<li>jquery UI datepicker</li>
<li>5 different mediaelement assets (js + css)</li>
<li>underscore.js</li>
<li>wp-embed js</li>
<li>wp-util js</li>
</ol>
| [
{
"answer_id": 243388,
"author": "Niels van Renselaar",
"author_id": 67313,
"author_profile": "https://wordpress.stackexchange.com/users/67313",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure what more you need that the example there, and remember that some scripts are needed... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243384",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51704/"
] | I want to dequeue all styles and scripts that are loaded on the front-end (EG. not the admin panel) by default.
I found this [function](https://codex.wordpress.org/Function_Reference/wp_dequeue_script), but am not sure how to utilize it to accomplish my goal.
I'm seeing a ton of assets that I don't need on the front end, loaded by WP core:
For example:
1. backbone.js
2. jquery UI
3. jquery UI datepicker
4. 5 different mediaelement assets (js + css)
5. underscore.js
6. wp-embed js
7. wp-util js | I'm not sure what more you need that the example there, and remember that some scripts are needed for stuff like the admin bar and are not enqueued if you are not logged in.
```
function wpdocs_dequeue_script() {
wp_dequeue_script( 'jquery-ui-core' );
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );
```
This will dequeue the jquery-ui-core js. Adding more lines of 'wp\_dequeue\_script' with the JS you want to dequeue will remove them aswel. You can find all the handles trough a dump of $wp\_scripts.
```
<?php global $wp_scripts; var_dump($wp_scripts); ?>
``` |
243,396 | <p>I am adding a new query string parameter to be passed into the URL so that I can manipulate the REST API responses.</p>
<p>I added this to my <code>functions.php</code></p>
<pre><code>add_filter('query_vars', function ($vars) {
$vars[] = 'xyz';
return $vars;
});
</code></pre>
<p>This should make the parameter <code>xyz</code> available in the WP_Query object but it does not.</p>
<pre><code>add_filter('pre_get_posts', function ($query) {
var_dump($query->query_vars);die;
});
</code></pre>
<p>The <code>xyz</code> property is not available in the <code>query_vars</code> however if I dump out the PHP $_GET array, it is there and has the value that I passed in, so I don't know why it wouldn't be making it into the <code>query_vars</code>. Any ideas?</p>
| [
{
"answer_id": 243413,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure it quite works like that. Try inspecting <code>$query->public_query_vars</code> ... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243396",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102669/"
] | I am adding a new query string parameter to be passed into the URL so that I can manipulate the REST API responses.
I added this to my `functions.php`
```
add_filter('query_vars', function ($vars) {
$vars[] = 'xyz';
return $vars;
});
```
This should make the parameter `xyz` available in the WP\_Query object but it does not.
```
add_filter('pre_get_posts', function ($query) {
var_dump($query->query_vars);die;
});
```
The `xyz` property is not available in the `query_vars` however if I dump out the PHP $\_GET array, it is there and has the value that I passed in, so I don't know why it wouldn't be making it into the `query_vars`. Any ideas? | I'm not sure it quite works like that. Try inspecting `$query->public_query_vars` instead and I think you'll see it added in there.
The way I usually use it is like this:
```
add_filter( 'query_vars', 'add_test_query_vars');
function add_test_query_vars($vars){
$vars[] = "test";
return $vars;
}
```
So the same as you but with a named function.
Then I add a rewrite endpoint:
```
function wpse_243396_endpoint() {
add_rewrite_endpoint( 'test', EP_PERMALINK );
}
add_action( 'init', 'wpse_243396_endpoint' );
```
And after that URLs ending `/test/` set the query var which I test like this:
```
global $wp_query;
if( isset( $wp_query->query['test'] ) ) { }
``` |
243,403 | <p>I am working on a new site but I am using the users from an old site.</p>
<p>I created all my user roles, which match the user roles on the other site. I deleted the user and usermeta table from the new site and imported these tables from the old site.</p>
<p>I can now see all the users and I can login with the users. The issue I have is that the users, other than the primary admin, have no roles assigned. </p>
<p>When I check the database, I do see the proper role assigned to them.</p>
<pre><code>'2039843', '308', 'wp_capabilities', 'a:1:{s:10:"subscriber";b:1;}'
</code></pre>
<p>When I am in the Users section of WordPress, I can see all the users but they have no roles "assigned" to them (even though it clearly is defined in the dataabase). </p>
<p>I am importing over 40,000 users so the database option seems the most fitting for my needs. Is there a snippet of code I can do to update this total perhaps? Where are these totals stored? I can tell, it's not scanning the usermeta table for these values so it has to be in the options table. </p>
<p>I already added the option for <code>wp_user_roles</code> and assigned it the same value as the old site, still no luck. No roles have totals and no users are assigned to the roles.</p>
<p>What is the best method to update the user role totals so WordPress will recognize the users are assigned properly to the roles?</p>
| [
{
"answer_id": 243413,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure it quite works like that. Try inspecting <code>$query->public_query_vars</code> ... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19217/"
] | I am working on a new site but I am using the users from an old site.
I created all my user roles, which match the user roles on the other site. I deleted the user and usermeta table from the new site and imported these tables from the old site.
I can now see all the users and I can login with the users. The issue I have is that the users, other than the primary admin, have no roles assigned.
When I check the database, I do see the proper role assigned to them.
```
'2039843', '308', 'wp_capabilities', 'a:1:{s:10:"subscriber";b:1;}'
```
When I am in the Users section of WordPress, I can see all the users but they have no roles "assigned" to them (even though it clearly is defined in the dataabase).
I am importing over 40,000 users so the database option seems the most fitting for my needs. Is there a snippet of code I can do to update this total perhaps? Where are these totals stored? I can tell, it's not scanning the usermeta table for these values so it has to be in the options table.
I already added the option for `wp_user_roles` and assigned it the same value as the old site, still no luck. No roles have totals and no users are assigned to the roles.
What is the best method to update the user role totals so WordPress will recognize the users are assigned properly to the roles? | I'm not sure it quite works like that. Try inspecting `$query->public_query_vars` instead and I think you'll see it added in there.
The way I usually use it is like this:
```
add_filter( 'query_vars', 'add_test_query_vars');
function add_test_query_vars($vars){
$vars[] = "test";
return $vars;
}
```
So the same as you but with a named function.
Then I add a rewrite endpoint:
```
function wpse_243396_endpoint() {
add_rewrite_endpoint( 'test', EP_PERMALINK );
}
add_action( 'init', 'wpse_243396_endpoint' );
```
And after that URLs ending `/test/` set the query var which I test like this:
```
global $wp_query;
if( isset( $wp_query->query['test'] ) ) { }
``` |
243,408 | <p>I don't know how to turn some WP QUERY parameters into url query strings. Most of them are straight forward, but there are some I don't know how to get working. For example, for these WP_QUERY parameters:</p>
<pre><code>$args = array(
'post_type' => 'post',
's' => 'keyword',
);
</code></pre>
<p>the query string for this is: <code>?s=keyword&post_type=post</code></p>
<p>What is the query string for the 'after' parameter with value '24 hours ago'. For example, this WP_QUERY gets posts created in the last 24 hours:</p>
<pre><code>$args = array(
'date_query' => array(
array(
'after' => '24 hours ago',
),
),
);
</code></pre>
<p>But I don't know the query string for it. This doesn't work:</p>
<pre><code>?after=24%20hours%20ago
</code></pre>
<p>Any help appreciated.</p>
| [
{
"answer_id": 243413,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure it quite works like that. Try inspecting <code>$query->public_query_vars</code> ... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243408",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88767/"
] | I don't know how to turn some WP QUERY parameters into url query strings. Most of them are straight forward, but there are some I don't know how to get working. For example, for these WP\_QUERY parameters:
```
$args = array(
'post_type' => 'post',
's' => 'keyword',
);
```
the query string for this is: `?s=keyword&post_type=post`
What is the query string for the 'after' parameter with value '24 hours ago'. For example, this WP\_QUERY gets posts created in the last 24 hours:
```
$args = array(
'date_query' => array(
array(
'after' => '24 hours ago',
),
),
);
```
But I don't know the query string for it. This doesn't work:
```
?after=24%20hours%20ago
```
Any help appreciated. | I'm not sure it quite works like that. Try inspecting `$query->public_query_vars` instead and I think you'll see it added in there.
The way I usually use it is like this:
```
add_filter( 'query_vars', 'add_test_query_vars');
function add_test_query_vars($vars){
$vars[] = "test";
return $vars;
}
```
So the same as you but with a named function.
Then I add a rewrite endpoint:
```
function wpse_243396_endpoint() {
add_rewrite_endpoint( 'test', EP_PERMALINK );
}
add_action( 'init', 'wpse_243396_endpoint' );
```
And after that URLs ending `/test/` set the query var which I test like this:
```
global $wp_query;
if( isset( $wp_query->query['test'] ) ) { }
``` |
243,423 | <p>I want to add a button to TinyMCE editor, which opens Media Uploader of WordPress. I have used <code>wp_editor()</code>. Here is my code-</p>
<pre><code>$editor = array(
'textarea_name' => 'message',
'media_buttons' => false,
'textarea_rows' => 8,
'quicktags' => false,
'drag_drop_upload' => true,
'tinymce' => array(
'paste_as_text' => true,
'paste_auto_cleanup_on_paste' => true,
'paste_remove_spans' => true,
'paste_remove_styles' => true,
'paste_remove_styles_if_webkit' => true,
'paste_strip_class_attributes' => true,
'toolbar1' => 'bold italic | superscript subscript | bullist numlist | forecolor backcolor | link unlink | image media | visualblocks undo redo code',
'toolbar2' => '',
'toolbar3' => '',
'toolbar4' => ''
),
);
wp_editor( '', 'message', $editor );
</code></pre>
<p>I want an icon to be shown here-
<a href="https://i.stack.imgur.com/ZXe4Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZXe4Q.png" alt="enter image description here"></a></p>
<p>How do I do this? Thanks in advance.</p>
| [
{
"answer_id": 243413,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure it quite works like that. Try inspecting <code>$query->public_query_vars</code> ... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243423",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57944/"
] | I want to add a button to TinyMCE editor, which opens Media Uploader of WordPress. I have used `wp_editor()`. Here is my code-
```
$editor = array(
'textarea_name' => 'message',
'media_buttons' => false,
'textarea_rows' => 8,
'quicktags' => false,
'drag_drop_upload' => true,
'tinymce' => array(
'paste_as_text' => true,
'paste_auto_cleanup_on_paste' => true,
'paste_remove_spans' => true,
'paste_remove_styles' => true,
'paste_remove_styles_if_webkit' => true,
'paste_strip_class_attributes' => true,
'toolbar1' => 'bold italic | superscript subscript | bullist numlist | forecolor backcolor | link unlink | image media | visualblocks undo redo code',
'toolbar2' => '',
'toolbar3' => '',
'toolbar4' => ''
),
);
wp_editor( '', 'message', $editor );
```
I want an icon to be shown here-
[](https://i.stack.imgur.com/ZXe4Q.png)
How do I do this? Thanks in advance. | I'm not sure it quite works like that. Try inspecting `$query->public_query_vars` instead and I think you'll see it added in there.
The way I usually use it is like this:
```
add_filter( 'query_vars', 'add_test_query_vars');
function add_test_query_vars($vars){
$vars[] = "test";
return $vars;
}
```
So the same as you but with a named function.
Then I add a rewrite endpoint:
```
function wpse_243396_endpoint() {
add_rewrite_endpoint( 'test', EP_PERMALINK );
}
add_action( 'init', 'wpse_243396_endpoint' );
```
And after that URLs ending `/test/` set the query var which I test like this:
```
global $wp_query;
if( isset( $wp_query->query['test'] ) ) { }
``` |
243,428 | <p>I want to modify wordpress's core files to get a desired result for cropping and saving uploaded images. However, i can't find the function that handles the uploaded images and crops, renames and saves them.</p>
<p>I thought this function may have something to do with thumbnails :<code>wp_generate_attachment_metadata</code></p>
<p>Can anyone help me which file and function does this?
Thank you</p>
| [
{
"answer_id": 243413,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure it quite works like that. Try inspecting <code>$query->public_query_vars</code> ... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243428",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94498/"
] | I want to modify wordpress's core files to get a desired result for cropping and saving uploaded images. However, i can't find the function that handles the uploaded images and crops, renames and saves them.
I thought this function may have something to do with thumbnails :`wp_generate_attachment_metadata`
Can anyone help me which file and function does this?
Thank you | I'm not sure it quite works like that. Try inspecting `$query->public_query_vars` instead and I think you'll see it added in there.
The way I usually use it is like this:
```
add_filter( 'query_vars', 'add_test_query_vars');
function add_test_query_vars($vars){
$vars[] = "test";
return $vars;
}
```
So the same as you but with a named function.
Then I add a rewrite endpoint:
```
function wpse_243396_endpoint() {
add_rewrite_endpoint( 'test', EP_PERMALINK );
}
add_action( 'init', 'wpse_243396_endpoint' );
```
And after that URLs ending `/test/` set the query var which I test like this:
```
global $wp_query;
if( isset( $wp_query->query['test'] ) ) { }
``` |
243,436 | <p>I'm using a weird SELECT query to calculate the average of all the post ratings (stored in <code>wp_postmeta</code>) for a certain user.</p>
<p>My query basically uses the following arguments:</p>
<blockquote>
<p><code>post_author = 1</code> AND <code>meta_key = 'rating'</code> AND <code>meta_value != 0</code>.</p>
</blockquote>
<p>This query works perfectly fine on it's own, but here's where it gets complicated. I need to add some exceptions...</p>
<blockquote>
<p><code>meta_key = 'anonymous'</code> AND <code>meta_value != 'true'</code></p>
</blockquote>
<p>And another...</p>
<blockquote>
<p><code>meta_key = 'original_author'</code> AND <code>meta_value = ''</code></p>
</blockquote>
<p>I want to retrieve only the <code>rating</code> meta_values, so I'll probably run into more problems using <code>$wpdb->postmeta.meta_value</code>.</p>
<p>This totals up to 3 <code>meta_key</code> and <code>meta_value</code> arguments, with only one <code>meta_value</code> that I actually want to retrieve. It just gets more and more tricky...</p>
<p>See my code below:</p>
<pre><code>// Example value
$user_id = 1;
// Calculate average post rating for user
$ratings_query = $wpdb->get_results(
$wpdb->prepare("
SELECT $wpdb->postmeta.meta_value
FROM $wpdb->postmeta
JOIN $wpdb->posts ON ($wpdb->postmeta.post_id = $wpdb->posts.id)
WHERE (
$wpdb->posts.post_author = %d AND
$wpdb->posts.post_type = 'post' AND
$wpdb->posts.post_status = 'publish' AND
$wpdb->postmeta.meta_key = 'rating' AND
$wpdb->postmeta.meta_value != 0
AND
$wpdb->postmeta.meta_key = 'anonymous' AND
$wpdb->postmeta.meta_value != 'true'
AND
$wpdb->postmeta.meta_key = 'original_author' AND
$wpdb->postmeta.meta_value = '')
", $user_id), ARRAY_N);
if ( $ratings_query ) {
$ratings_query = call_user_func_array('array_merge', $ratings_query);
$average_rating = round(array_sum($ratings_query) / count($ratings_query), 1);
} else {
$average_rating = 0;
}
</code></pre>
| [
{
"answer_id": 243413,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure it quite works like that. Try inspecting <code>$query->public_query_vars</code> ... | 2016/10/20 | [
"https://wordpress.stackexchange.com/questions/243436",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22588/"
] | I'm using a weird SELECT query to calculate the average of all the post ratings (stored in `wp_postmeta`) for a certain user.
My query basically uses the following arguments:
>
> `post_author = 1` AND `meta_key = 'rating'` AND `meta_value != 0`.
>
>
>
This query works perfectly fine on it's own, but here's where it gets complicated. I need to add some exceptions...
>
> `meta_key = 'anonymous'` AND `meta_value != 'true'`
>
>
>
And another...
>
> `meta_key = 'original_author'` AND `meta_value = ''`
>
>
>
I want to retrieve only the `rating` meta\_values, so I'll probably run into more problems using `$wpdb->postmeta.meta_value`.
This totals up to 3 `meta_key` and `meta_value` arguments, with only one `meta_value` that I actually want to retrieve. It just gets more and more tricky...
See my code below:
```
// Example value
$user_id = 1;
// Calculate average post rating for user
$ratings_query = $wpdb->get_results(
$wpdb->prepare("
SELECT $wpdb->postmeta.meta_value
FROM $wpdb->postmeta
JOIN $wpdb->posts ON ($wpdb->postmeta.post_id = $wpdb->posts.id)
WHERE (
$wpdb->posts.post_author = %d AND
$wpdb->posts.post_type = 'post' AND
$wpdb->posts.post_status = 'publish' AND
$wpdb->postmeta.meta_key = 'rating' AND
$wpdb->postmeta.meta_value != 0
AND
$wpdb->postmeta.meta_key = 'anonymous' AND
$wpdb->postmeta.meta_value != 'true'
AND
$wpdb->postmeta.meta_key = 'original_author' AND
$wpdb->postmeta.meta_value = '')
", $user_id), ARRAY_N);
if ( $ratings_query ) {
$ratings_query = call_user_func_array('array_merge', $ratings_query);
$average_rating = round(array_sum($ratings_query) / count($ratings_query), 1);
} else {
$average_rating = 0;
}
``` | I'm not sure it quite works like that. Try inspecting `$query->public_query_vars` instead and I think you'll see it added in there.
The way I usually use it is like this:
```
add_filter( 'query_vars', 'add_test_query_vars');
function add_test_query_vars($vars){
$vars[] = "test";
return $vars;
}
```
So the same as you but with a named function.
Then I add a rewrite endpoint:
```
function wpse_243396_endpoint() {
add_rewrite_endpoint( 'test', EP_PERMALINK );
}
add_action( 'init', 'wpse_243396_endpoint' );
```
And after that URLs ending `/test/` set the query var which I test like this:
```
global $wp_query;
if( isset( $wp_query->query['test'] ) ) { }
``` |
243,448 | <p>I am trying to figure out the best way to do something similar with <a href="http://getbootstrap.com/javascript/" rel="nofollow noreferrer">http://getbootstrap.com/javascript/</a>
<a href="https://i.stack.imgur.com/Dn0Ms.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dn0Ms.jpg" alt="enter image description here"></a></p>
<p>I understand that I have to use scrollspy and work on couple jQuery line for "scroll-to" thing and also working with affix, I have no problem doing that on static page.</p>
<p>On the post of WordPress, I want to have an "index" where the reader can jump from one section to another (exactly like the getbootstrap page). </p>
<p>What I don't know is how to generate this on the post dynamically, since</p>
<ul>
<li>Each post will have a different index name</li>
<li>Each post will have a different amount of index.</li>
<li>Each post will have a different id name.</li>
</ul>
<p>I am looking for using Advance Custom Field.</p>
<p>Anyone has an experience on this or can help?</p>
| [
{
"answer_id": 243413,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure it quite works like that. Try inspecting <code>$query->public_query_vars</code> ... | 2016/10/21 | [
"https://wordpress.stackexchange.com/questions/243448",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105375/"
] | I am trying to figure out the best way to do something similar with <http://getbootstrap.com/javascript/>
[](https://i.stack.imgur.com/Dn0Ms.jpg)
I understand that I have to use scrollspy and work on couple jQuery line for "scroll-to" thing and also working with affix, I have no problem doing that on static page.
On the post of WordPress, I want to have an "index" where the reader can jump from one section to another (exactly like the getbootstrap page).
What I don't know is how to generate this on the post dynamically, since
* Each post will have a different index name
* Each post will have a different amount of index.
* Each post will have a different id name.
I am looking for using Advance Custom Field.
Anyone has an experience on this or can help? | I'm not sure it quite works like that. Try inspecting `$query->public_query_vars` instead and I think you'll see it added in there.
The way I usually use it is like this:
```
add_filter( 'query_vars', 'add_test_query_vars');
function add_test_query_vars($vars){
$vars[] = "test";
return $vars;
}
```
So the same as you but with a named function.
Then I add a rewrite endpoint:
```
function wpse_243396_endpoint() {
add_rewrite_endpoint( 'test', EP_PERMALINK );
}
add_action( 'init', 'wpse_243396_endpoint' );
```
And after that URLs ending `/test/` set the query var which I test like this:
```
global $wp_query;
if( isset( $wp_query->query['test'] ) ) { }
``` |
243,476 | <p>I want to exclude some specific post types from generating sitemaps in yoast seo plugin. Please provide suggestions to do this. Thanks in advance.</p>
| [
{
"answer_id": 280973,
"author": "iMarkDesigns",
"author_id": 88981,
"author_profile": "https://wordpress.stackexchange.com/users/88981",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using <code>functions.php</code> script to register custom post type, you should declare <cod... | 2016/10/21 | [
"https://wordpress.stackexchange.com/questions/243476",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105401/"
] | I want to exclude some specific post types from generating sitemaps in yoast seo plugin. Please provide suggestions to do this. Thanks in advance. | If you are using `functions.php` script to register custom post type, you should declare `false` to `'has_archive' => true,`.
```
function custom_post_type() {
$labels = array( ... );
$args = array(
// you have to set it to False.
'has_archive' => false,
);
register_post_type( 'post_type', $args );
}
add_action( 'init', 'custom_post_type', 0 );
``` |
243,482 | <p>I have a function which processes custom metabox data on saving my custom post type:</p>
<pre><code>add_action('save_post_customtypehere','myown_save_customtype_fn');
function myown_save_customtype_fn($ID) { ... }
</code></pre>
<p>However, the function also runs when I trash items within this CPT (I guess it's effectively saving the post to change <code>post_status</code> to <code>trash</code>). Without the metabox being present, my function ends up clearing things like <code>post_name</code> (not great if I need to restore from trash!).</p>
<p>I have two thoughts but can't quite get across the finishing line with them:</p>
<p>1) In order to update post data I use <code>remove_action()</code> and <code>add_action()</code> again around <code>wp_update_post(array('post_key'=>$sanitized_form_input))</code> - as per the codex instructions, this is required to avoid an infinite loop. Could there be a similar way of excluding from a trash_post action (I already tried <code>remove_action('trash_post','myown_save_customtype_fn'</code> immediately after the original <code>add_action</code> line).</p>
<p>2) Is there something I can use in a conditional within <code>myown_save_customtype_fn</code> (along the lines of <code>if (current action!='trash_post') { ...</code>)</p>
| [
{
"answer_id": 243483,
"author": "websupporter",
"author_id": 48693,
"author_profile": "https://wordpress.stackexchange.com/users/48693",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow\"><code>save... | 2016/10/21 | [
"https://wordpress.stackexchange.com/questions/243482",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101959/"
] | I have a function which processes custom metabox data on saving my custom post type:
```
add_action('save_post_customtypehere','myown_save_customtype_fn');
function myown_save_customtype_fn($ID) { ... }
```
However, the function also runs when I trash items within this CPT (I guess it's effectively saving the post to change `post_status` to `trash`). Without the metabox being present, my function ends up clearing things like `post_name` (not great if I need to restore from trash!).
I have two thoughts but can't quite get across the finishing line with them:
1) In order to update post data I use `remove_action()` and `add_action()` again around `wp_update_post(array('post_key'=>$sanitized_form_input))` - as per the codex instructions, this is required to avoid an infinite loop. Could there be a similar way of excluding from a trash\_post action (I already tried `remove_action('trash_post','myown_save_customtype_fn'` immediately after the original `add_action` line).
2) Is there something I can use in a conditional within `myown_save_customtype_fn` (along the lines of `if (current action!='trash_post') { ...`) | [`save_post`](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) gets fired, once the post is saved. We get the current post object as the second parameter. So we can check, if the current post status is trash:
```
<?php
add_action( 'save_post', function( $post_ID, $post, $update ) {
if ( 'trash' === $post->post_status ) {
return;
}
/** do your stuff **/
}, 10, 3 );
?>
``` |
243,516 | <p>I was able to add part of the in product description with this code:</p>
<pre><code>function get_ecommerce_excerpt(){
$excerpt = get_the_excerpt();
$excerpt = preg_replace(" ([.*?])",'',$excerpt);
$excerpt = strip_shortcodes($excerpt);
$excerpt = strip_tags($excerpt);
$excerpt = substr($excerpt, 0, 100);
$excerpt = substr($excerpt, 0, strripos($excerpt, " "));
$excerpt = trim(preg_replace( '/s+/', ' ', $excerpt));
return $excerpt;
}
</code></pre>
<p>The problem is that that's not what I'm actually trying to do. </p>
<p>What I'm trying to do is use a custom field area named Brief Description to add 2 lines of whatever text I write inside the field. </p>
<p>Is there a code that I can't use to do this?</p>
| [
{
"answer_id": 243587,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>The brief description of a WooCommerce product is store as post_excerpt, to programmatically add some text, yo... | 2016/10/21 | [
"https://wordpress.stackexchange.com/questions/243516",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60721/"
] | I was able to add part of the in product description with this code:
```
function get_ecommerce_excerpt(){
$excerpt = get_the_excerpt();
$excerpt = preg_replace(" ([.*?])",'',$excerpt);
$excerpt = strip_shortcodes($excerpt);
$excerpt = strip_tags($excerpt);
$excerpt = substr($excerpt, 0, 100);
$excerpt = substr($excerpt, 0, strripos($excerpt, " "));
$excerpt = trim(preg_replace( '/s+/', ' ', $excerpt));
return $excerpt;
}
```
The problem is that that's not what I'm actually trying to do.
What I'm trying to do is use a custom field area named Brief Description to add 2 lines of whatever text I write inside the field.
Is there a code that I can't use to do this? | The brief description of a WooCommerce product is store as post\_excerpt, to programmatically add some text, you need to hook through product excerpt.
```
add_filter('get_the_excerpt', 'custom_excerpt');
function exc($custom_excerpt) {
global $post;
if($post->post_type == 'product'){
$custom_add = __('This product is unavailable for some countries, please, read our terms & conditions to know more about this.', 'folkstone');
return $excerpt . $custom_add;
}else{
return $excerpt;
}
}
``` |
243,518 | <p>I am using WordPress 4.6.1 .</p>
<p>Everything was working fine then suddenly I started getting a error message " <strong>403 Access Denied</strong> " when I tried to access new post using link of post.
I tried different method to check what is causing the error but not able to find.</p>
<p>No error is coming in old, Only getting error in new post that I am posting from last one week.</p>
<p>Here is my Error Log which I found on my web hosting site-</p>
<blockquote>
<p>Thu, 20 Oct 2016 15:45:22 -0500 AH01797: client denied by server configuration: /home/vol1_4/byethost5.com/b5_18545859/example.com/htdocs/chatbot</p>
</blockquote>
<blockquote>
<p>Thu, 20 Oct 2016 15:45:32 -0500 AH01797: client denied by server configuration: /home/vol1_4/byethost5.com/b5_18545859/example.com/htdocs/build-a-chatbot-without-coding</p>
</blockquote>
<p>Here is my .htaccess file details-</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
| [
{
"answer_id": 243519,
"author": "Ryan Konkolewski",
"author_id": 105426,
"author_profile": "https://wordpress.stackexchange.com/users/105426",
"pm_score": 0,
"selected": false,
"text": "<p>I've come across a similar problem before. I suggest disabling all plugins and seeing if this reso... | 2016/10/21 | [
"https://wordpress.stackexchange.com/questions/243518",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105427/"
] | I am using WordPress 4.6.1 .
Everything was working fine then suddenly I started getting a error message " **403 Access Denied** " when I tried to access new post using link of post.
I tried different method to check what is causing the error but not able to find.
No error is coming in old, Only getting error in new post that I am posting from last one week.
Here is my Error Log which I found on my web hosting site-
>
> Thu, 20 Oct 2016 15:45:22 -0500 AH01797: client denied by server configuration: /home/vol1\_4/byethost5.com/b5\_18545859/example.com/htdocs/chatbot
>
>
>
>
> Thu, 20 Oct 2016 15:45:32 -0500 AH01797: client denied by server configuration: /home/vol1\_4/byethost5.com/b5\_18545859/example.com/htdocs/build-a-chatbot-without-coding
>
>
>
Here is my .htaccess file details-
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
``` | Generate your `.htaccess` again. For that go to `Settings >> Permalinks` then hit `Save Changes` button. It will re-generate your `.htaccess` file. If it's no resolved, you can try the `FTP` described in comment by @Benoti. If that's also not worked please try [this blog](http://www.wpbeginner.com/wp-tutorials/how-to-fix-the-403-forbidden-error-in-wordpress/). |
243,522 | <p>I have a multisite network set up with around 250 sites. I'd like to be able to copy users with their assigned role from the main site in the network to subsites. Here is how I attempted to do this:</p>
<p><strong>functions.php</strong></p>
<pre><code>add_action('wp','add_current_user_to_site',10);
function add_current_user_to_site() {
if(!is_user_logged_in()) {
return false;
}
$current_user = wp_get_current_user();
$blog_id = get_current_blog_id();
$user_id = ($current_user->ID);
switch_to_blog(1);
$get_role = ($current_user->caps);
$add_role = key($get_role);
restore_current_blog();
if (!is_user_member_of_blog( $user_id, $blog_id ) ) {
add_user_to_blog( $blog_id, $user_id, $add_role );
}
}
</code></pre>
<p>This has been tested and works when a user visits the subsite THEN proceeds to log in. If they attempt to log in directly, they receive an error.</p>
<p>Is this the best way to set up copying a user and adding them to subsites? Is there a way to allow it to happen when visiting the login directly, rather than needing to visit the site first?</p>
| [
{
"answer_id": 243558,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the below function to copy all the users to all the subsite. It's actually getting all the use... | 2016/10/21 | [
"https://wordpress.stackexchange.com/questions/243522",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88515/"
] | I have a multisite network set up with around 250 sites. I'd like to be able to copy users with their assigned role from the main site in the network to subsites. Here is how I attempted to do this:
**functions.php**
```
add_action('wp','add_current_user_to_site',10);
function add_current_user_to_site() {
if(!is_user_logged_in()) {
return false;
}
$current_user = wp_get_current_user();
$blog_id = get_current_blog_id();
$user_id = ($current_user->ID);
switch_to_blog(1);
$get_role = ($current_user->caps);
$add_role = key($get_role);
restore_current_blog();
if (!is_user_member_of_blog( $user_id, $blog_id ) ) {
add_user_to_blog( $blog_id, $user_id, $add_role );
}
}
```
This has been tested and works when a user visits the subsite THEN proceeds to log in. If they attempt to log in directly, they receive an error.
Is this the best way to set up copying a user and adding them to subsites? Is there a way to allow it to happen when visiting the login directly, rather than needing to visit the site first? | Using the other answer provided, it appears there are two ways to copy users with their assigned roles from the main site to subsites in a WordPress multisite network.
It can be set up to either add the current user or all users from a site (I chose the main network site, `blog_id=1`) to the subsite when they visit the page.
Here is how to do both, choose one and add to `functions.php`:
**Add only the user to each subsite**
```
function add_current_user_to_site() {
if(!is_user_logged_in()) {
return false;
}
$current_user = wp_get_current_user();
$blog_id = get_current_blog_id();
$user_id = ($current_user->ID);
switch_to_blog(1);
$get_role = ($current_user->caps);
$add_role = key($get_role);
restore_current_blog();
if (!is_user_member_of_blog( $user_id, $blog_id ) ) {
add_user_to_blog( $blog_id, $user_id, $add_role );
}
}
add_action('wp','add_current_user_to_site');
```
---
**Add all users to each subsite**
```
function add_all_users_to_site() {
if(!is_user_logged_in()) {
return false;
}
$users = get_users('blog_id=1');
$sites = get_sites();
foreach ($sites as $site) {
foreach ($users as $user) {
$blog_id = get_current_blog_id();
$user_id = ($user->ID);
switch_to_blog($site->id);
$get_role = ($user->caps);
$add_role = key($get_role);
restore_current_blog();
if (!is_user_member_of_blog( $user_id, $blog_id ) ) {
add_user_to_blog( $blog_id, $user_id, $add_role );
}
}
}
}
add_action('wp','add_all_users_to_site');
``` |
243,537 | <p>So I'm working on a custom save-post filter. It's working to handle the external API calls I'm using to generate information, which is super awesome. In total, I'm grabbing file info from an API, downloading a couple of files, writing them to a directory, zipping them and deleting them. It all works. During this process I'm extracting data points from the API stuff and storing them as variables to be saved as meta fields. My function looks like this, minus all of the stuff you don't need to see (assume that the function works EXCEPT update_post_meta() isn't firing). </p>
<pre><code>function stuff_save( $post_id ) {
$post_type = get_post_type($post_id);
// If this is just a revision, do nothing.
if ( wp_is_post_revision( $post_id )|| "animations" != $post_type )
return;
/**code to generate data points**/
$datapoint = get_post_meta($post_id,custom_field,1);
$update_var= string_from_API_Call;
/**uses $datapoint to do a thing; I'm using this result elsewhere, can echo it, and it's successful.**/
$hat = update_post_meta( $post_id, 'field_name', $update_var );//returns a value, but that number doesn't correspond with any meta key in my database nor does the data save anywhere.
}
}add_action( 'save_post', 'stuff_save' );
</code></pre>
<p>Now if I echo $hat it returns a number, like it would - but that meta key not only doesn't exist when I look into my post_meta table, but it increments when I refresh the script just the same. </p>
<p>Little help overflowvians?</p>
| [
{
"answer_id": 243551,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 0,
"selected": false,
"text": "<p>I think the main problem is in the <code>if</code> block. It does <code>return</code> before executing <co... | 2016/10/21 | [
"https://wordpress.stackexchange.com/questions/243537",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57332/"
] | So I'm working on a custom save-post filter. It's working to handle the external API calls I'm using to generate information, which is super awesome. In total, I'm grabbing file info from an API, downloading a couple of files, writing them to a directory, zipping them and deleting them. It all works. During this process I'm extracting data points from the API stuff and storing them as variables to be saved as meta fields. My function looks like this, minus all of the stuff you don't need to see (assume that the function works EXCEPT update\_post\_meta() isn't firing).
```
function stuff_save( $post_id ) {
$post_type = get_post_type($post_id);
// If this is just a revision, do nothing.
if ( wp_is_post_revision( $post_id )|| "animations" != $post_type )
return;
/**code to generate data points**/
$datapoint = get_post_meta($post_id,custom_field,1);
$update_var= string_from_API_Call;
/**uses $datapoint to do a thing; I'm using this result elsewhere, can echo it, and it's successful.**/
$hat = update_post_meta( $post_id, 'field_name', $update_var );//returns a value, but that number doesn't correspond with any meta key in my database nor does the data save anywhere.
}
}add_action( 'save_post', 'stuff_save' );
```
Now if I echo $hat it returns a number, like it would - but that meta key not only doesn't exist when I look into my post\_meta table, but it increments when I refresh the script just the same.
Little help overflowvians? | I solved my own problem.
save-post hooks in before the form is saved. It even gives us access to the $\_POST object and allows us to interact with it before the original save happens.
What this means essentially is that I'm overwriting my values with blank formdata.
Rather than updating post meta, I've documented and am writing to the $\_POST object the updated values, which are then submitted as part of the original save post.
```
$hat = update_post_meta( $post_id, 'field_name', $update_var );
```
Becomes
```
/**document this well or you'll drive someone insane in the future.**/
$_POST['field_name'] = $update_var;
```
Thanks everyone for your thoughts and attempts to help. You no doubt inspired me to think about it. |
243,541 | <p>In order to query products based on custom fields, from the plugin advanced custom fields, i have to use this wp query script, to query it correctly.</p>
<p>However, when i copied this script, changed the needed values, and inserted it into functions.php, it crashes the site. </p>
<p>I believe its a parse or syntax error because its using a lot of . I have tried removing some of them, still no results.
When all the other scripts above it has been removed (irrelevant), then it looks like this:</p>
<pre><code> <?php
<?php
add_action( 'wp_ajax_posts_by_brand_action', 'posts_by_brand_action_callback' );
function posts_by_brand_action_callback() {
global $wpdb; // this is how you get access to the database
$brand = $_POST['brand'];
echo $whatever;
// ----- START OF BRAND FILTER CODE
// args
$args = array(
//'numberposts' => -1,
//'post_type' => 'event',
'meta_key' => 'brand',
'meta_value' => $brand
);
// query
$the_query = new WP_Query( $args );
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
// ------ END OF BRAND FILTER CODE
wp_die(); // this is required to terminate immediately and return a proper response
}
?>
</code></pre>
<p>How do i go a about this? Would it be correct to say, that shouldn't be used inside an ?</p>
| [
{
"answer_id": 243542,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 2,
"selected": false,
"text": "<p>It's hard to debug only seeing a portion of your code.</p>\n\n<p>For starters, you've got two <code><?php</c... | 2016/10/22 | [
"https://wordpress.stackexchange.com/questions/243541",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77322/"
] | In order to query products based on custom fields, from the plugin advanced custom fields, i have to use this wp query script, to query it correctly.
However, when i copied this script, changed the needed values, and inserted it into functions.php, it crashes the site.
I believe its a parse or syntax error because its using a lot of . I have tried removing some of them, still no results.
When all the other scripts above it has been removed (irrelevant), then it looks like this:
```
<?php
<?php
add_action( 'wp_ajax_posts_by_brand_action', 'posts_by_brand_action_callback' );
function posts_by_brand_action_callback() {
global $wpdb; // this is how you get access to the database
$brand = $_POST['brand'];
echo $whatever;
// ----- START OF BRAND FILTER CODE
// args
$args = array(
//'numberposts' => -1,
//'post_type' => 'event',
'meta_key' => 'brand',
'meta_value' => $brand
);
// query
$the_query = new WP_Query( $args );
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
// ------ END OF BRAND FILTER CODE
wp_die(); // this is required to terminate immediately and return a proper response
}
?>
```
How do i go a about this? Would it be correct to say, that shouldn't be used inside an ? | It's hard to debug only seeing a portion of your code.
For starters, you've got two `<?php` opening tags at the top which would certainly cause an error. But I think that's leftover from your copy and paste.
* Look at your php server log which will tell you what file and line number the error is occurring.
* Put the following in your `wp-config.php` file which will print all errors in your browser. Then you won't have to access the php log directly.
Code to add:
```
define( 'WP_DEBUG', true );
```
[WordPress Debugging Guide](https://codex.wordpress.org/Debugging_in_WordPress#WP_DEBUG) |
243,545 | <p>i am a little confused how to use escape function on a variable having html code in it. i have tried this
<a href="https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data" rel="nofollow">https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data</a>
but i could not figure it out.
here is my code:</p>
<pre><code> $output = '<p>';
$output .= '<label for="' . esc_attr( $this->get_field_id( 'title' ) ) . '">Title:</label>';
$output .= '<input type="text" class="widefat" id="' . esc_attr( $this->get_field_id( 'title' ) ) . '" name="' . esc_attr( $this->get_field_name( 'title' ) ) . '" value="' . esc_attr( $title ) . '"';
$output .= '</p>';
echo $output;
</code></pre>
<p>My question is how i can escape $output without losing html in it?
i am asking because i am submitting this code on themeforest. from where i have been rejected few times because of not escaping code. So now i think it is better to escape there variables. write?
thank you!</p>
| [
{
"answer_id": 243547,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 0,
"selected": false,
"text": "<p>Your code looks and works fine for me. The HTML in <code>value</code> is preserved.</p>\n\n<p>My only recommend... | 2016/10/22 | [
"https://wordpress.stackexchange.com/questions/243545",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105445/"
] | i am a little confused how to use escape function on a variable having html code in it. i have tried this
<https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data>
but i could not figure it out.
here is my code:
```
$output = '<p>';
$output .= '<label for="' . esc_attr( $this->get_field_id( 'title' ) ) . '">Title:</label>';
$output .= '<input type="text" class="widefat" id="' . esc_attr( $this->get_field_id( 'title' ) ) . '" name="' . esc_attr( $this->get_field_name( 'title' ) ) . '" value="' . esc_attr( $title ) . '"';
$output .= '</p>';
echo $output;
```
My question is how i can escape $output without losing html in it?
i am asking because i am submitting this code on themeforest. from where i have been rejected few times because of not escaping code. So now i think it is better to escape there variables. write?
thank you! | You are looking for `wp_kses()`. <https://developer.wordpress.org/reference/functions/wp_kses/>
There are more helper functions like `wp_kses_post()` and `wp_kses_data()` |
243,573 | <p>I am importing an rss feed from a job listing site and creating a post for each listing i import with wp_insert_post to save the data and display expired listings in an archive later. </p>
<p>I need a solution to keep wp_insert_post from creating duplicats while it still updates the post if certain values have been updated on the job listing from the feed. Each listing has its own ID called AdvertID from the feed. </p>
<p>Just to clearify,"if (!get_page_by_title)" wont do the trick when a lot of job listings can have the same title, so that solution ends up excluding a majority of listings. Everything works fine with the code already there, i just need a solution to the problems i am explaining. Just showing some code so you can get a sense of what i am doing here. `
<pre><code> $post = array(
'post_content' => $item->description,
'post_date' => $item_date,
'post_title' => $item_title,
'post_status' => 'publish',
'post_type' => 'jobs',
);
$id = wp_insert_post($post);
$metdata = array(
'link' => $item->link,
'date' => $item ->date,
'company_logo_path' => $item->CompanyLogoPath,
'company_profile_text' => $item->CompanyProfileText,
</code></pre>
| [
{
"answer_id": 243547,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 0,
"selected": false,
"text": "<p>Your code looks and works fine for me. The HTML in <code>value</code> is preserved.</p>\n\n<p>My only recommend... | 2016/10/22 | [
"https://wordpress.stackexchange.com/questions/243573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105461/"
] | I am importing an rss feed from a job listing site and creating a post for each listing i import with wp\_insert\_post to save the data and display expired listings in an archive later.
I need a solution to keep wp\_insert\_post from creating duplicats while it still updates the post if certain values have been updated on the job listing from the feed. Each listing has its own ID called AdvertID from the feed.
Just to clearify,"if (!get\_page\_by\_title)" wont do the trick when a lot of job listings can have the same title, so that solution ends up excluding a majority of listings. Everything works fine with the code already there, i just need a solution to the problems i am explaining. Just showing some code so you can get a sense of what i am doing here. `
```
$post = array(
'post_content' => $item->description,
'post_date' => $item_date,
'post_title' => $item_title,
'post_status' => 'publish',
'post_type' => 'jobs',
);
$id = wp_insert_post($post);
$metdata = array(
'link' => $item->link,
'date' => $item ->date,
'company_logo_path' => $item->CompanyLogoPath,
'company_profile_text' => $item->CompanyProfileText,
``` | You are looking for `wp_kses()`. <https://developer.wordpress.org/reference/functions/wp_kses/>
There are more helper functions like `wp_kses_post()` and `wp_kses_data()` |
243,588 | <p>I would like to query and sort posts by meta key "popularity" and these posts must have also another meta key "gone" with value "1" to query</p>
<pre><code>$args = array(
'post_status' => 'publish',
'posts_per_page' => '150',
'cat' => $cat_id,
'order' => 'DESC'
'meta_query' => array(
'relation' => 'AND',
'popularity' => array(
'key' => 'popularity',
'orderby' => 'meta_value_num',
),
'be_price' => array(
'key' => 'gone',
'value' => '1'
)
)
);
</code></pre>
| [
{
"answer_id": 243547,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 0,
"selected": false,
"text": "<p>Your code looks and works fine for me. The HTML in <code>value</code> is preserved.</p>\n\n<p>My only recommend... | 2016/10/22 | [
"https://wordpress.stackexchange.com/questions/243588",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97811/"
] | I would like to query and sort posts by meta key "popularity" and these posts must have also another meta key "gone" with value "1" to query
```
$args = array(
'post_status' => 'publish',
'posts_per_page' => '150',
'cat' => $cat_id,
'order' => 'DESC'
'meta_query' => array(
'relation' => 'AND',
'popularity' => array(
'key' => 'popularity',
'orderby' => 'meta_value_num',
),
'be_price' => array(
'key' => 'gone',
'value' => '1'
)
)
);
``` | You are looking for `wp_kses()`. <https://developer.wordpress.org/reference/functions/wp_kses/>
There are more helper functions like `wp_kses_post()` and `wp_kses_data()` |
243,594 | <p>I am trying to add a custom info notice after the post has been deleted from the trash, but I'm not having any luck with it</p>
<pre><code>add_action( 'delete_post', 'show_admin_notice' );
/**
* Show admin notice after post delete
*
* @since 1.0.0.
*/
function show_admin_notice(){
add_action( 'admin_notices', 'show_post_order_info' );
}
/**
* Display notice when user deletes the post
*
* When user deletes the post, show the notice for the user
* to go and refresh the post order.
*
* @since 1.0.0
*/
function show_post_order_info() {
$screen = get_current_screen();
if ( $screen->id === 'edit-post' ) {
?>
<div class="notice notice-info is-dismissible">
<p><?php echo esc_html__( 'Please update the ', 'nwl' ) . '<a href="' . esc_url( admin_url( 'edit.php?page=post-order' ) ). '">' . esc_html__( 'post order settings', 'nwl' ) . '</a>' . esc_html__( ' so that the posts would be correctly ordered on the front pages.', 'nwl' ); ?></p>
</div>
<?php
}
}
</code></pre>
<p>I'm clearly missing something here, but I couldn't find out what on the google.</p>
<p>If I just use the <code>admin_notices</code> hook, I'll get the notice shown always on my posts admin page</p>
| [
{
"answer_id": 243602,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>I think this will solve:</p>\n\n<pre><code>if(isset($_GET['post_status']) && $_GET['post_status']=='t... | 2016/10/22 | [
"https://wordpress.stackexchange.com/questions/243594",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58895/"
] | I am trying to add a custom info notice after the post has been deleted from the trash, but I'm not having any luck with it
```
add_action( 'delete_post', 'show_admin_notice' );
/**
* Show admin notice after post delete
*
* @since 1.0.0.
*/
function show_admin_notice(){
add_action( 'admin_notices', 'show_post_order_info' );
}
/**
* Display notice when user deletes the post
*
* When user deletes the post, show the notice for the user
* to go and refresh the post order.
*
* @since 1.0.0
*/
function show_post_order_info() {
$screen = get_current_screen();
if ( $screen->id === 'edit-post' ) {
?>
<div class="notice notice-info is-dismissible">
<p><?php echo esc_html__( 'Please update the ', 'nwl' ) . '<a href="' . esc_url( admin_url( 'edit.php?page=post-order' ) ). '">' . esc_html__( 'post order settings', 'nwl' ) . '</a>' . esc_html__( ' so that the posts would be correctly ordered on the front pages.', 'nwl' ); ?></p>
</div>
<?php
}
}
```
I'm clearly missing something here, but I couldn't find out what on the google.
If I just use the `admin_notices` hook, I'll get the notice shown always on my posts admin page | Checking the bulk counts
------------------------
We can check the *bulk counts*, to see if any post was *deleted*:
```
add_filter( 'bulk_post_updated_messages', function( $bulk_messages, $bulk_counts )
{
// Check the bulk counts for 'deleted' and add notice if it's gt 0
if( isset( $bulk_counts['deleted'] ) && $bulk_counts['deleted'] > 0 )
add_filter( 'admin_notices', 'wpse_243594_notice' );
return $bulk_messages;
}, 10, 2 );
```
where we define the callback with our custom notice as:
```
function wpse_243594_notice()
{
printf(
'<div class="notice notice-info is-dismissible">%s</div>',
esc_html__( 'Hello World!', 'domain' )
);
}
```
The bulk counts contains further info for *updated*, *locked*, *trashed* and *untrashed*.
Output example
--------------
[](https://i.stack.imgur.com/xlJWm.jpg)
Hope you can adjust this further to your needs! |
243,615 | <p>I have multiple selected box within my nav menus i used <code>add_post_meta()</code> for adding values and <code>delete_post_meta</code> for deleting selected options. the code work, means add and delete options correctly but i have small problem</p>
<p>When i delete options <code>delete_post_meta()</code> delete selected options except the first one means also remain one of them and i can't delete it</p>
<p>How i can manage this code below until delete all selected options?</p>
<pre><code>if(!empty($_REQUEST['menu-item-custom-category'][$menu_item_db_id])) {
delete_post_meta($menu_item_db_id, '_menu_item_custom_category');
$values = $_REQUEST['menu-item-custom-category'][$menu_item_db_id];
foreach($values as $value) {
add_post_meta($menu_item_db_id, '_menu_item_custom_category', $value);
}
}
$item->custom_category = get_post_meta( $item->ID, '_menu_item_custom_content');
</code></pre>
<p>This is my multiple select box</p>
<pre><code><p class="field-custom-category description description-thin">
<label for="edit-menu-item-custom-category-<?php echo $item_id; ?>">
<?php _e( 'Custom Categories' ); ?><br />
<select name="menu-item-custom-category[<?php echo $item_id; ?>][]" id="edit-menu-item-custom-category-<?php echo $item_id; ?>" class="widefat code edit-menu-item-custom-category" multiple>
<?php
$YPE_cats = get_categories();
foreach ($YPE_cats as $YPE_cat) { ?>
<option value="<?php echo $YPE_cat->slug; ?>" <?php echo selected(in_array($YPE_cat->slug, $item->custom_category)); ?>><?php echo $YPE_cat->name;?></option><?php
}
?>
</select>
</label>
</p>
</code></pre>
| [
{
"answer_id": 243621,
"author": "SAFEEN 1990",
"author_id": 82436,
"author_profile": "https://wordpress.stackexchange.com/users/82436",
"pm_score": 0,
"selected": false,
"text": "<p>Before selecting any value you don't have an <code>array()</code> means you must select options until the... | 2016/10/22 | [
"https://wordpress.stackexchange.com/questions/243615",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37216/"
] | I have multiple selected box within my nav menus i used `add_post_meta()` for adding values and `delete_post_meta` for deleting selected options. the code work, means add and delete options correctly but i have small problem
When i delete options `delete_post_meta()` delete selected options except the first one means also remain one of them and i can't delete it
How i can manage this code below until delete all selected options?
```
if(!empty($_REQUEST['menu-item-custom-category'][$menu_item_db_id])) {
delete_post_meta($menu_item_db_id, '_menu_item_custom_category');
$values = $_REQUEST['menu-item-custom-category'][$menu_item_db_id];
foreach($values as $value) {
add_post_meta($menu_item_db_id, '_menu_item_custom_category', $value);
}
}
$item->custom_category = get_post_meta( $item->ID, '_menu_item_custom_content');
```
This is my multiple select box
```
<p class="field-custom-category description description-thin">
<label for="edit-menu-item-custom-category-<?php echo $item_id; ?>">
<?php _e( 'Custom Categories' ); ?><br />
<select name="menu-item-custom-category[<?php echo $item_id; ?>][]" id="edit-menu-item-custom-category-<?php echo $item_id; ?>" class="widefat code edit-menu-item-custom-category" multiple>
<?php
$YPE_cats = get_categories();
foreach ($YPE_cats as $YPE_cat) { ?>
<option value="<?php echo $YPE_cat->slug; ?>" <?php echo selected(in_array($YPE_cat->slug, $item->custom_category)); ?>><?php echo $YPE_cat->name;?></option><?php
}
?>
</select>
</label>
</p>
``` | I think it is just a matter of logic. If you don't select any value, `$_REQUEST['menu-item-custom-category'][$menu_item_db_id]` is empty. So, the next line `delete_post_meta()` is never triggered in your code. Just think in the logic you need to know when to delete previous meta value.
For example:
```
if( !empty( $_REQUEST['menu-item-custom-category'][$menu_item_db_id] ) ) {
// Delete all previous values from database and save
// only the selected values in the current request
delete_post_meta( $menu_item_db_id, '_menu_item_custom_category' );
$values = $_REQUEST['menu-item-custom-category'][$menu_item_db_id];
if( is_array( $values ) ) {
// We have several values
// Sanitize values first (needed if you have not registered a sanitization callback with register_meta())
$values = array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) );
foreach( $values as $value ) {
add_post_meta( $menu_item_db_id, '_menu_item_custom_category', $value );
}
} else {
// We have single value
add_post_meta( $menu_item_db_id, '_menu_item_custom_category', sanitize_text_field( $values ) );
}
} else {
// All values unselected, delete all of them from post meta
delete_post_meta($menu_item_db_id, '_menu_item_custom_category');
}
```
This could be optimized, so only new values are added and only deselected values are deleted, without deleting and adding everything everytime. For example (based on [this answer](https://wordpress.stackexchange.com/a/107556/37428)):
```
if ( empty( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) ) {
// no values selected, delete all post meta for our key
delete_post_meta( $menu_item_db_id, '_menu_item_content_multiple' );
} else {
$old_values = get_post_meta( $menu_item_db_id, '_menu_item_custom_category' );
$new_values = $_REQUEST['menu-item-content-multiple'][$menu_item_db_id]
$values_to_skip = array();
if( !empty( $old_values ) ) {
foreach( $old_values as $old_value ) {
if ( ! in_array( $old_value, $new_values ) ) {
// this value was in meta, but now it is not selected,
// so it has to be deletec
delete_post_meta( $menu_item_db_id, '_menu_item_custom_category', $old_value );
} else {
// This value was in meta and it is selected again,
// So, we don't need to save it again
$values_to_skip[] = $old_value;
}
}
}
// Get the values that are not already in database
// And store them
$values_to_save = array_diff( $new_values, $values_to_skip );
if ( ! empty( $values_to_save ) ) {
foreach ( $values_to_save as $value ) {
add_post_meta( $menu_item_db_id, '_menu_item_content_multiple', $value );
}
}
}
``` |
243,617 | <p>I want to create custom thumbnail dialogues for the homepage of my WordPress installation.</p>
<p>This is what I want to achieve:<a href="https://i.stack.imgur.com/6J4ud.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6J4ud.png" alt="image"></a></p>
<p>This is the bootstrap code for the image above:</p>
<pre><code><div class="row">
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="..." alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>...</p>
<p>
<a href="#" class="btn btn-primary" role="button">Button</a>
<a href="#" class="btn btn-default" role="button">Button</a>
</p>
</div>
</div>
</div>
</div>
</code></pre>
<p>So until now, I have the code below and I can't have the content in a single line. </p>
<pre><code><div class="row">
<div class="col-sm-6 col-md-4">
<?php // theloop
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php// Define our WP Query Parameters ?>
<?php $the_query = new WP_Query( 'posts_per_page=3' ); ?>
<?php// Start our WP Query ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<div class="thumbnail"><?php the_post_thumbnail(array(100, 100)); ?>
<div class="caption">
<?php// Display the Post Title with Hyperlink?>
<h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
<?php// Repeat the process and reset once it hits the limit
</div>
</div>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</code></pre>
<p>The screenshot below reflects the result of my current code (non-desirable):
<a href="https://i.stack.imgur.com/uRYWn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uRYWn.png" alt="image"></a></p>
<p>How can I make it?</p>
| [
{
"answer_id": 243621,
"author": "SAFEEN 1990",
"author_id": 82436,
"author_profile": "https://wordpress.stackexchange.com/users/82436",
"pm_score": 0,
"selected": false,
"text": "<p>Before selecting any value you don't have an <code>array()</code> means you must select options until the... | 2016/10/22 | [
"https://wordpress.stackexchange.com/questions/243617",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48024/"
] | I want to create custom thumbnail dialogues for the homepage of my WordPress installation.
This is what I want to achieve:[](https://i.stack.imgur.com/6J4ud.png)
This is the bootstrap code for the image above:
```
<div class="row">
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="..." alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>...</p>
<p>
<a href="#" class="btn btn-primary" role="button">Button</a>
<a href="#" class="btn btn-default" role="button">Button</a>
</p>
</div>
</div>
</div>
</div>
```
So until now, I have the code below and I can't have the content in a single line.
```
<div class="row">
<div class="col-sm-6 col-md-4">
<?php // theloop
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php// Define our WP Query Parameters ?>
<?php $the_query = new WP_Query( 'posts_per_page=3' ); ?>
<?php// Start our WP Query ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<div class="thumbnail"><?php the_post_thumbnail(array(100, 100)); ?>
<div class="caption">
<?php// Display the Post Title with Hyperlink?>
<h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
<?php// Repeat the process and reset once it hits the limit
</div>
</div>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
```
The screenshot below reflects the result of my current code (non-desirable):
[](https://i.stack.imgur.com/uRYWn.png)
How can I make it? | I think it is just a matter of logic. If you don't select any value, `$_REQUEST['menu-item-custom-category'][$menu_item_db_id]` is empty. So, the next line `delete_post_meta()` is never triggered in your code. Just think in the logic you need to know when to delete previous meta value.
For example:
```
if( !empty( $_REQUEST['menu-item-custom-category'][$menu_item_db_id] ) ) {
// Delete all previous values from database and save
// only the selected values in the current request
delete_post_meta( $menu_item_db_id, '_menu_item_custom_category' );
$values = $_REQUEST['menu-item-custom-category'][$menu_item_db_id];
if( is_array( $values ) ) {
// We have several values
// Sanitize values first (needed if you have not registered a sanitization callback with register_meta())
$values = array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) );
foreach( $values as $value ) {
add_post_meta( $menu_item_db_id, '_menu_item_custom_category', $value );
}
} else {
// We have single value
add_post_meta( $menu_item_db_id, '_menu_item_custom_category', sanitize_text_field( $values ) );
}
} else {
// All values unselected, delete all of them from post meta
delete_post_meta($menu_item_db_id, '_menu_item_custom_category');
}
```
This could be optimized, so only new values are added and only deselected values are deleted, without deleting and adding everything everytime. For example (based on [this answer](https://wordpress.stackexchange.com/a/107556/37428)):
```
if ( empty( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) ) {
// no values selected, delete all post meta for our key
delete_post_meta( $menu_item_db_id, '_menu_item_content_multiple' );
} else {
$old_values = get_post_meta( $menu_item_db_id, '_menu_item_custom_category' );
$new_values = $_REQUEST['menu-item-content-multiple'][$menu_item_db_id]
$values_to_skip = array();
if( !empty( $old_values ) ) {
foreach( $old_values as $old_value ) {
if ( ! in_array( $old_value, $new_values ) ) {
// this value was in meta, but now it is not selected,
// so it has to be deletec
delete_post_meta( $menu_item_db_id, '_menu_item_custom_category', $old_value );
} else {
// This value was in meta and it is selected again,
// So, we don't need to save it again
$values_to_skip[] = $old_value;
}
}
}
// Get the values that are not already in database
// And store them
$values_to_save = array_diff( $new_values, $values_to_skip );
if ( ! empty( $values_to_save ) ) {
foreach ( $values_to_save as $value ) {
add_post_meta( $menu_item_db_id, '_menu_item_content_multiple', $value );
}
}
}
``` |
243,633 | <p>I'm starting to build a WordPress theme from scratch. I have MAMP all loaded and running on my computer and WordPress is loaded fine. I have the below three files all in the same folder </p>
<p>C:/MAMP/htdocs/wordpress/wp-content/themes/testtheme</p>
<p>The problem is I can't get the hook in the functions file to actually run the css code in the index file. As far as I can tell, it should. The functions and enqueue's all seem correct. So why wont these files communicate? </p>
<p>index.php</p>
<pre><code><html>
<head>
</head>
<body>
<h1>Hello World</h1>
<p class="once">This is an attempt at getting the functions file to work with the css files</p>
<p class="twice">Why wont this work...</p>
</body>
</code></pre>
<p></p>
<p>style.css</p>
<pre><code>/*
Theme Name: Test Theme
Description: This is a test to see if I can make a theme
Author: Ryan
Author URI: ###
version: 1.0
Template: ABC
*/
h1{
color: red;
}
.once{
text-align: canter;
background-color: gray;
}
.twice{
color: blue;
}
</code></pre>
<p>functions.php</p>
<pre><code><?php
function theme_resources() {
wp_enqueue_style('style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'theme_resources');
?>
</code></pre>
| [
{
"answer_id": 243634,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Your theme has to call <code>wp_head()</code> in the head section of the html (probably best to place it ... | 2016/10/23 | [
"https://wordpress.stackexchange.com/questions/243633",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105486/"
] | I'm starting to build a WordPress theme from scratch. I have MAMP all loaded and running on my computer and WordPress is loaded fine. I have the below three files all in the same folder
C:/MAMP/htdocs/wordpress/wp-content/themes/testtheme
The problem is I can't get the hook in the functions file to actually run the css code in the index file. As far as I can tell, it should. The functions and enqueue's all seem correct. So why wont these files communicate?
index.php
```
<html>
<head>
</head>
<body>
<h1>Hello World</h1>
<p class="once">This is an attempt at getting the functions file to work with the css files</p>
<p class="twice">Why wont this work...</p>
</body>
```
style.css
```
/*
Theme Name: Test Theme
Description: This is a test to see if I can make a theme
Author: Ryan
Author URI: ###
version: 1.0
Template: ABC
*/
h1{
color: red;
}
.once{
text-align: canter;
background-color: gray;
}
.twice{
color: blue;
}
```
functions.php
```
<?php
function theme_resources() {
wp_enqueue_style('style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'theme_resources');
?>
``` | Your theme has to call `wp_head()` in the head section of the html (probably best to place it at the end of it) and `wp_footer()` somewhere in your footer section. Those are **mandatory** function calls for all themes that want to be able to integrate with plugins and some core functionality like enqueuing JS and CSS depends on them.
If you do a "plain" HTML page, you have to manually insert the various CSS and JS into the HTML. |
243,672 | <p>Does anybody have experienced this issue:
using admin_url() in add_menu_page() returns an url that contains the domain name twice:</p>
<pre><code>add_submenu_page(
'smart-crm',
__('WP SMART CRM Documents', 'mytextdomain'),
__('Documents', 'mytextdomain'),
'manage_options',
admin_url('admin.php?page=smart-crm&p=documenti/list.php'),
''
);
</code></pre>
<p>My output link is : <a href="https://domain.com/domain.com/wp-admin/admin.php?page=smart-crm&p=documenti/list.php" rel="nofollow">https://domain.com/domain.com/wp-admin/admin.php?page=smart-crm&p=documenti/list.php</a></p>
<p>any idea?</p>
| [
{
"answer_id": 243634,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Your theme has to call <code>wp_head()</code> in the head section of the html (probably best to place it ... | 2016/10/23 | [
"https://wordpress.stackexchange.com/questions/243672",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64435/"
] | Does anybody have experienced this issue:
using admin\_url() in add\_menu\_page() returns an url that contains the domain name twice:
```
add_submenu_page(
'smart-crm',
__('WP SMART CRM Documents', 'mytextdomain'),
__('Documents', 'mytextdomain'),
'manage_options',
admin_url('admin.php?page=smart-crm&p=documenti/list.php'),
''
);
```
My output link is : <https://domain.com/domain.com/wp-admin/admin.php?page=smart-crm&p=documenti/list.php>
any idea? | Your theme has to call `wp_head()` in the head section of the html (probably best to place it at the end of it) and `wp_footer()` somewhere in your footer section. Those are **mandatory** function calls for all themes that want to be able to integrate with plugins and some core functionality like enqueuing JS and CSS depends on them.
If you do a "plain" HTML page, you have to manually insert the various CSS and JS into the HTML. |
243,687 | <p>I am struggling with getting post queries by coordinates. I have meta fields <code>map_lat</code> and <code>map_lng</code> for almost all post types. I am trying to return posts from one custom post type ("beaches" in this example):</p>
<pre><code>function get_nearby_locations($lat, $long, $distance){
global $wpdb;
$nearbyLocations = $wpdb->get_results(
"SELECT DISTINCT
map_lat.post_id,
map_lat.meta_key,
map_lat.meta_value as locLat,
map_lng.meta_value as locLong,
((ACOS(SIN($lat * PI() / 180) * SIN(map_lat.meta_value * PI() / 180) + COS($lat * PI() / 180) * COS(map_lat.meta_value * PI() / 180) * COS(($long - map_lng.meta_value) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance,
wp_posts.post_title
FROM
wp_postmeta AS map_lat
LEFT JOIN wp_postmeta as map_lng ON map_lat.post_id = map_lng.post_id
INNER JOIN wp_posts ON wp_posts.ID = map_lat.post_id
WHERE map_lat.meta_key = 'map_lat' AND map_lng.meta_key = 'map_lng'
AND post_type='beaches'
HAVING distance < $distance
ORDER BY distance ASC;"
);
if($nearbyLocations){
return $nearbyLocations;
}
}
</code></pre>
<p>and im calling it with:</p>
<pre><code>$nearbyLocation = get_nearby_cities(get_post_meta($post->ID, 'map_lat', true), get_post_meta($post->ID, 'map_lng', true), 25);
</code></pre>
<p>but it doesn't return what I want.</p>
| [
{
"answer_id": 243688,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 4,
"selected": true,
"text": "<p>Close. You need another <code>INNER JOIN</code> and should escape all your variables using <code>$wpdb->prepa... | 2016/10/23 | [
"https://wordpress.stackexchange.com/questions/243687",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105189/"
] | I am struggling with getting post queries by coordinates. I have meta fields `map_lat` and `map_lng` for almost all post types. I am trying to return posts from one custom post type ("beaches" in this example):
```
function get_nearby_locations($lat, $long, $distance){
global $wpdb;
$nearbyLocations = $wpdb->get_results(
"SELECT DISTINCT
map_lat.post_id,
map_lat.meta_key,
map_lat.meta_value as locLat,
map_lng.meta_value as locLong,
((ACOS(SIN($lat * PI() / 180) * SIN(map_lat.meta_value * PI() / 180) + COS($lat * PI() / 180) * COS(map_lat.meta_value * PI() / 180) * COS(($long - map_lng.meta_value) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance,
wp_posts.post_title
FROM
wp_postmeta AS map_lat
LEFT JOIN wp_postmeta as map_lng ON map_lat.post_id = map_lng.post_id
INNER JOIN wp_posts ON wp_posts.ID = map_lat.post_id
WHERE map_lat.meta_key = 'map_lat' AND map_lng.meta_key = 'map_lng'
AND post_type='beaches'
HAVING distance < $distance
ORDER BY distance ASC;"
);
if($nearbyLocations){
return $nearbyLocations;
}
}
```
and im calling it with:
```
$nearbyLocation = get_nearby_cities(get_post_meta($post->ID, 'map_lat', true), get_post_meta($post->ID, 'map_lng', true), 25);
```
but it doesn't return what I want. | Close. You need another `INNER JOIN` and should escape all your variables using `$wpdb->prepare`.
I've also included a more efficient Haversine formula ([source](https://developers.google.com/maps/articles/phpsqlsearch_v3#findnearsql)) to calculate the radius.
If you use kilometers, then change the `$earth_radius` to 6371.
Also, a great way to debug is to echo the sql and paste it into phpMyAdmin (or whatever db app you use) and tweak it in there.
```
function get_nearby_locations( $lat, $lng, $distance ) {
global $wpdb;
// Radius of the earth 3959 miles or 6371 kilometers.
$earth_radius = 3959;
$sql = $wpdb->prepare( "
SELECT DISTINCT
p.ID,
p.post_title,
map_lat.meta_value as locLat,
map_lng.meta_value as locLong,
( %d * acos(
cos( radians( %s ) )
* cos( radians( map_lat.meta_value ) )
* cos( radians( map_lng.meta_value ) - radians( %s ) )
+ sin( radians( %s ) )
* sin( radians( map_lat.meta_value ) )
) )
AS distance
FROM $wpdb->posts p
INNER JOIN $wpdb->postmeta map_lat ON p.ID = map_lat.post_id
INNER JOIN $wpdb->postmeta map_lng ON p.ID = map_lng.post_id
WHERE 1 = 1
AND p.post_type = 'beaches'
AND p.post_status = 'publish'
AND map_lat.meta_key = 'map_lat'
AND map_lng.meta_key = 'map_lng'
HAVING distance < %s
ORDER BY distance ASC",
$earth_radius,
$lat,
$lng,
$lat,
$distance
);
// Uncomment and paste into phpMyAdmin to debug.
// echo $sql;
$nearbyLocations = $wpdb->get_results( $sql );
if ( $nearbyLocations ) {
return $nearbyLocations;
}
}
``` |
243,703 | <p>I’m tryin to insert shortcode through add_action :</p>
<pre><code>add_action('woocommerce_single_product_summary', 'quotation_form', 61);
function quotation_form()
{
$produk = get_the_title();
$shortkode = sprintf(
'[zendesk_request_form size="3" group="extra-field" subject="Quotation For %s"]',
$produk
);
$shortkode = do_shortcode( $shortkode );
echo $shortkode;
}
</code></pre>
<p>But gettin error after the shortcode displayed:</p>
<blockquote>
<p>Uncaught Error: Call to a member function get_upsells() on null in /home/dev/wp-content/themes/dummy-child/woocommerce/single-product/up-sells.php:25 </p>
</blockquote>
<p>The line related with error above:</p>
<pre><code>if ( ! $upsells = $product->get_upsells() ) {
return;
}
</code></pre>
<p><code>Source: https://github.com/woocommerce/woocommerce/blob/master/templates/single-product/up-sells.php</code></p>
<p>So I think:</p>
<ol>
<li><p>The shortcode itself displaying properly but script stop executed with error above </p></li>
<li><p>When I tried to output <em>quotation_form</em> function with return /
echo-ing plain text or html, its working perfectly without any error</p></li>
</ol>
<p>My question is:
How the right way to insert shortcode in WooCommerce template?
Is it possible to doing that?</p>
<p>Thank you</p>
| [
{
"answer_id": 243712,
"author": "Pascal Knecht",
"author_id": 105101,
"author_profile": "https://wordpress.stackexchange.com/users/105101",
"pm_score": 1,
"selected": false,
"text": "<p>Your problem is that the $product variable is not defined. I see two possible solutions:</p>\n\n<ul>\... | 2016/10/24 | [
"https://wordpress.stackexchange.com/questions/243703",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88402/"
] | I’m tryin to insert shortcode through add\_action :
```
add_action('woocommerce_single_product_summary', 'quotation_form', 61);
function quotation_form()
{
$produk = get_the_title();
$shortkode = sprintf(
'[zendesk_request_form size="3" group="extra-field" subject="Quotation For %s"]',
$produk
);
$shortkode = do_shortcode( $shortkode );
echo $shortkode;
}
```
But gettin error after the shortcode displayed:
>
> Uncaught Error: Call to a member function get\_upsells() on null in /home/dev/wp-content/themes/dummy-child/woocommerce/single-product/up-sells.php:25
>
>
>
The line related with error above:
```
if ( ! $upsells = $product->get_upsells() ) {
return;
}
```
`Source: https://github.com/woocommerce/woocommerce/blob/master/templates/single-product/up-sells.php`
So I think:
1. The shortcode itself displaying properly but script stop executed with error above
2. When I tried to output *quotation\_form* function with return /
echo-ing plain text or html, its working perfectly without any error
My question is:
How the right way to insert shortcode in WooCommerce template?
Is it possible to doing that?
Thank you | I solved this with dirty way.. hope someone else can provide more efficient solution, my final working code for problem above:
```
$shortkode = '[zendesk_request_form size="3" group="extra-field" subject="Quotation For -wkwkwk-"]';
$shortkode = do_shortcode( $shortkode );
add_action('woocommerce_single_product_summary', 'quotation_form', 61);
function quotation_form()
{
$produk = get_the_title();
global $shortkode;
$shortkode = str_replace("-wkwkwk-", $produk, $shortkode);
echo $shortkode;
}
```
So i move out do\_shorcode outside function, then declare it as global variable.
The problem is about my $produk variable will not working if declare it outside Wordpress page, so I'm using str\_replace to replacing pre product title |
243,718 | <p><strong>UPDATE</strong> Refrased the question</p>
<p>On the backend widget page <code>widgets.php</code>, there is a list of available widgets. Items in this list have the same classes and a <a href="https://developer.wordpress.org/reference/functions/wp_list_widgets/" rel="nofollow">dynamically generated ID</a>, which changes if a new widget is inserted (alphabetically) into the list. So, there is no reliable way to direct css at individual items in the list.</p>
<p>Is there another way to style individual items in the widget list?</p>
<p><strong>Old, more narrow question</strong></p>
<p>I have a theme which includes a <a href="http://fontawesome.io/" rel="nofollow">font icon</a> in its full name. It's defined globally like this:</p>
<pre><code>$theme_data = wp_get_theme(); // Retrieves the theme data from style.css
$theme_name = $theme_data['Name'];
$theme_icon = '<i class="fa fa-wrench" style="font-family:FontAwesome;"></i>';
$theme_full_name = $theme_icon . ' ' . $theme_name;
</code></pre>
<p>I can use <code>$theme_full_name</code> in menus, page titles and so on. There's one exception, however. The theme includes two widgets, which also have <code>$theme_full_name</code> in their name (the second parameter <a href="https://codex.wordpress.org/Widgets_API" rel="nofollow">in the constructor</a>). On the <code>widgets.php</code> page in the admin only the theme name appears. Apparently the icon is stripped away (as is, presumably, all html that might be in the widget name).</p>
<p>Is there a way to retain the font icon in the widget name?</p>
| [
{
"answer_id": 243719,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": -1,
"selected": false,
"text": "<p>Indeed, all html is stripped from the widget name in the backend by this line (WP 4.6) in the <a href=\"https:/... | 2016/10/24 | [
"https://wordpress.stackexchange.com/questions/243718",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75495/"
] | **UPDATE** Refrased the question
On the backend widget page `widgets.php`, there is a list of available widgets. Items in this list have the same classes and a [dynamically generated ID](https://developer.wordpress.org/reference/functions/wp_list_widgets/), which changes if a new widget is inserted (alphabetically) into the list. So, there is no reliable way to direct css at individual items in the list.
Is there another way to style individual items in the widget list?
**Old, more narrow question**
I have a theme which includes a [font icon](http://fontawesome.io/) in its full name. It's defined globally like this:
```
$theme_data = wp_get_theme(); // Retrieves the theme data from style.css
$theme_name = $theme_data['Name'];
$theme_icon = '<i class="fa fa-wrench" style="font-family:FontAwesome;"></i>';
$theme_full_name = $theme_icon . ' ' . $theme_name;
```
I can use `$theme_full_name` in menus, page titles and so on. There's one exception, however. The theme includes two widgets, which also have `$theme_full_name` in their name (the second parameter [in the constructor](https://codex.wordpress.org/Widgets_API)). On the `widgets.php` page in the admin only the theme name appears. Apparently the icon is stripped away (as is, presumably, all html that might be in the widget name).
Is there a way to retain the font icon in the widget name? | Just as @MarkKaplun [mentioned](https://wordpress.stackexchange.com/questions/243718/can-i-individually-style-items-in-the-backend-widget-list/244667#comment363657_243719) in a comment, it's possible with CSS. Also with Javascript.
CSS Approach
------------
Let's look at the *Calendar* widget, as an example.
The *id* for the widget, in the *available widgets* list, is of the form:
```
widget-{integer}_calendar-__i__
```
and in the sidebar it's:
```
widget-{integer}_calendar-{integer}
```
If we want to display the [calendar dashicon](https://developer.wordpress.org/resource/dashicons/#calendar) before the widget title, then we can e.g. enqueue a custom stylesheet for the `widgets.php` file, with something like:
```
div[id*="_calendar-"].widget .widget-title h3:before{
content: "\f145"; font-family: dashicons; margin-right: 0.5rem;
}
```
Here we use `*=` to find a substring match within the id selector.
It will display like this:
[](https://i.stack.imgur.com/ao32U.jpg)
If needed we could restrict this further to the *right* or *left* parts:
```
#widgets-right
#widgets-left
```
or the available widgets:
```
#available-widgets
```
The `widgets.php` page will also have `body.widgets-php` if needed for general stylesheets. |
243,721 | <p>I want to query two post types: 'projects' all of them and 'posts' by taxonomy 'light'. Does someone know how can this be achieved?</p>
<p>Kris</p>
| [
{
"answer_id": 243733,
"author": "amit singh",
"author_id": 105452,
"author_profile": "https://wordpress.stackexchange.com/users/105452",
"pm_score": -1,
"selected": false,
"text": "<p>Have you registered any custom taxonomy for projects and posts? what is the slug of that taxonomy?</p>\... | 2016/10/24 | [
"https://wordpress.stackexchange.com/questions/243721",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105539/"
] | I want to query two post types: 'projects' all of them and 'posts' by taxonomy 'light'. Does someone know how can this be achieved?
Kris | I solved my problem by automatically adding the tag 'light' to all my projects. And then query all the post and projects with the light tag like this:
Query post by taxonomy tag 'light':
```
$args = array(
'post_type' => array( 'projects' , 'post' ),
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'post_tag',
'field' => 'name',
'terms' => 'light'
)
),
'post_status' => 'publish'
);
query_posts( $args );
```
Add tag 'light' to all projects on publish:
```
add_action('publish_projects', 'projects_post_type_tagging', 10, 2);
function projects_post_type_tagging($post_id, $post){
wp_set_post_terms( $post_id, 'light', 'post_tag', true );
}
```
It's not the most elegant solution but it works. If theres a better way to solve this problem i've would like to know. |
243,740 | <p>While building a custom theme, I've been stuck on how to add a CSS class to a certain theme menu (meaning a custom menu that is associated with a theme menu position).</p>
<p>So far, in my template I have</p>
<pre><code> <?php if (has_nav_menu('main-menu')) : ?>
<nav class="topmenu" role="navigation">
<?php
wp_nav_menu(array(
'menu-class' => 'topmenu--list',
'theme_location' => 'main-menu',
'fallback_cb' => false,
));
?>
</nav>
<?php endif; ?>
</code></pre>
<p>So, I'm sort of missing a <code>'menu-item-class'</code> option in the wp_nav_menu's <code>$args</code> array. How can I pass a CSS class to each menu item?</p>
<p>Just to be clear, I do not want an editor to set a CSS class to each menu item manually in admin backend. I want to add the CSS class to each menu item programmatically.</p>
| [
{
"answer_id": 243745,
"author": "Florin Sarba",
"author_id": 105556,
"author_profile": "https://wordpress.stackexchange.com/users/105556",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <code>nav_menu_css_class</code> filter which is applied to every menu item in the spec... | 2016/10/24 | [
"https://wordpress.stackexchange.com/questions/243740",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63707/"
] | While building a custom theme, I've been stuck on how to add a CSS class to a certain theme menu (meaning a custom menu that is associated with a theme menu position).
So far, in my template I have
```
<?php if (has_nav_menu('main-menu')) : ?>
<nav class="topmenu" role="navigation">
<?php
wp_nav_menu(array(
'menu-class' => 'topmenu--list',
'theme_location' => 'main-menu',
'fallback_cb' => false,
));
?>
</nav>
<?php endif; ?>
```
So, I'm sort of missing a `'menu-item-class'` option in the wp\_nav\_menu's `$args` array. How can I pass a CSS class to each menu item?
Just to be clear, I do not want an editor to set a CSS class to each menu item manually in admin backend. I want to add the CSS class to each menu item programmatically. | You can use the `nav_menu_css_class` filter which is applied to every menu item in the specified nav menu.
```
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class($classes, $item){
$classes[] = 'your-custom-class';
return $classes;
}
```
More info: <http://www.wpbeginner.com/wp-tutorials/add-a-custom-class-in-wordpress-menu-item-using-conditional-statements/> |
243,794 | <p>I have a Wordpress installation in the root directory of my host. It includes an SSL certificate for that primary domain (e.g. <code>domain.com</code>; not a wildcard certificate).</p>
<p>When I include <code>define('FORCE_SSL_ADMIN', true);</code> in wp-config.php, suddenly all subdomains also try to redirect to https, despite the fact that there is no SSL certificate for those subdomains.</p>
<p>Some of the subdomains are also Wordpress installs in subfolders of my host (e.g. <code>test.domain.com</code>), but others are hosted on completely separate hosts.</p>
<p>When I look at <code>chrome://net-internals/#hsts</code> I see:</p>
<pre><code>static_sts_domain:
static_upgrade_mode: UNKNOWN
static_sts_include_subdomains:
static_sts_observed:
static_pkp_domain:
static_pkp_include_subdomains:
static_pkp_observed:
static_spki_hashes:
dynamic_sts_domain: domain.com
dynamic_upgrade_mode: STRICT
dynamic_sts_include_subdomains: true
dynamic_sts_observed: 1477318558.379693
dynamic_pkp_domain:
dynamic_pkp_include_subdomains:
dynamic_pkp_observed:
dynamic_spki_hashes:
</code></pre>
<p>Why would FORCE_SSL_ADMIN affect <code>dynamic_sts_include_subdomains</code>? Is there any way around this, while still keeping adequate security in my WP Admin?</p>
| [
{
"answer_id": 243828,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": -1,
"selected": false,
"text": "<p>It sounds like you're using <a href=\"https://codex.wordpress.org/Create_A_Network\" rel=\"nofollow\">WordPres... | 2016/10/24 | [
"https://wordpress.stackexchange.com/questions/243794",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78022/"
] | I have a Wordpress installation in the root directory of my host. It includes an SSL certificate for that primary domain (e.g. `domain.com`; not a wildcard certificate).
When I include `define('FORCE_SSL_ADMIN', true);` in wp-config.php, suddenly all subdomains also try to redirect to https, despite the fact that there is no SSL certificate for those subdomains.
Some of the subdomains are also Wordpress installs in subfolders of my host (e.g. `test.domain.com`), but others are hosted on completely separate hosts.
When I look at `chrome://net-internals/#hsts` I see:
```
static_sts_domain:
static_upgrade_mode: UNKNOWN
static_sts_include_subdomains:
static_sts_observed:
static_pkp_domain:
static_pkp_include_subdomains:
static_pkp_observed:
static_spki_hashes:
dynamic_sts_domain: domain.com
dynamic_upgrade_mode: STRICT
dynamic_sts_include_subdomains: true
dynamic_sts_observed: 1477318558.379693
dynamic_pkp_domain:
dynamic_pkp_include_subdomains:
dynamic_pkp_observed:
dynamic_spki_hashes:
```
Why would FORCE\_SSL\_ADMIN affect `dynamic_sts_include_subdomains`? Is there any way around this, while still keeping adequate security in my WP Admin? | It turns out that the shared server I have at Network Solutions is forcing HSTS through their service. And since it's a shared hosting server, they refuse to change it.
The solution: I purchased a Wildcard certificate, and installed it on multiple servers for each subdomain. |
243,810 | <p>For my custom settings field, I am looking to insert it <a href="https://i.stack.imgur.com/Cds8f.png" rel="nofollow noreferrer">right after the <em>Site Address (URL)</em> field</a> in the <em>General</em> settings page.</p>
<p>I'm able to add the custom field sucessfully using the <code>add_settings_field()</code>. Be default, it add the custom field <a href="https://i.stack.imgur.com/MYryA.png" rel="nofollow noreferrer">at the bottom</a>. Using jQuery, I was able to display my custom field after the <em>Site Address (URL)</em>:</p>
<pre><code>add_action( 'admin_footer', 'wpse_243810_admin_footer' );
function wpse_243810_admin_footer() {
?>
<script type="text/javascript">
jQuery('#protocol_relative').closest('tr').insertAfter('#home-description').closest('tr');
</script>
<?php
}
</code></pre>
<p>However, it looks like the following instead:</p>
<p><img src="https://i.stack.imgur.com/O7YlK.png" alt=""></p>
<p>Looking at the code, it inserts my custom field within the Site Address field's <code><tr></code> element. How get I have it inserted outide of it instead? Below are the seperate code snippets of each field.</p>
<pre><code><tr>
<th scope="row"><label for="home">Site Address (URL)</label></th>
<td>
<input name="home" type="url" id="home" aria-describedby="home-description" value="http://example.com" class="regular-text code">
<p class="description" id="home-description">Enter the address here if you <a href="//codex.wordpress.org/Giving_WordPress_Its_Own_Directory">want your site home page to be different from your WordPress installation directory.</a></p>
</td>
</tr>
</code></pre>
<p>This is the custom field that my plugin generates which I want ot insert after:</p>
<pre><code><tr>
<th scope="row">Protocol Relative URL</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Protocol Relative URL</span></legend>
<label for="remove_http">
<input name="protocol_relative" type="checkbox" id="protocol_relative" value="1" checked="checked">Do not apply to external links
</label>
<p class="description">Only the internal links will be affected.</p>
</fieldset>
</td>
</tr>
</code></pre>
| [
{
"answer_id": 243814,
"author": "wassereimer",
"author_id": 54551,
"author_profile": "https://wordpress.stackexchange.com/users/54551",
"pm_score": 0,
"selected": false,
"text": "<p>I think that this is not possible without modifying the core-files. We only have one time <code>do_settin... | 2016/10/24 | [
"https://wordpress.stackexchange.com/questions/243810",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] | For my custom settings field, I am looking to insert it [right after the *Site Address (URL)* field](https://i.stack.imgur.com/Cds8f.png) in the *General* settings page.
I'm able to add the custom field sucessfully using the `add_settings_field()`. Be default, it add the custom field [at the bottom](https://i.stack.imgur.com/MYryA.png). Using jQuery, I was able to display my custom field after the *Site Address (URL)*:
```
add_action( 'admin_footer', 'wpse_243810_admin_footer' );
function wpse_243810_admin_footer() {
?>
<script type="text/javascript">
jQuery('#protocol_relative').closest('tr').insertAfter('#home-description').closest('tr');
</script>
<?php
}
```
However, it looks like the following instead:

Looking at the code, it inserts my custom field within the Site Address field's `<tr>` element. How get I have it inserted outide of it instead? Below are the seperate code snippets of each field.
```
<tr>
<th scope="row"><label for="home">Site Address (URL)</label></th>
<td>
<input name="home" type="url" id="home" aria-describedby="home-description" value="http://example.com" class="regular-text code">
<p class="description" id="home-description">Enter the address here if you <a href="//codex.wordpress.org/Giving_WordPress_Its_Own_Directory">want your site home page to be different from your WordPress installation directory.</a></p>
</td>
</tr>
```
This is the custom field that my plugin generates which I want ot insert after:
```
<tr>
<th scope="row">Protocol Relative URL</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Protocol Relative URL</span></legend>
<label for="remove_http">
<input name="protocol_relative" type="checkbox" id="protocol_relative" value="1" checked="checked">Do not apply to external links
</label>
<p class="description">Only the internal links will be affected.</p>
</fieldset>
</td>
</tr>
``` | Figured it out by using the following jQuery function. The `#protocol_relative` is the field I am inserting and `#home-description` is the field I am inserting it after:
```
add_action( 'admin_footer', 'insert_field' );
function insert_field() {
# Insert the settings field after the 'Site Address (URL)'
?> <script type="text/javascript">
jQuery( '#protocol_relative' ).closest( 'tr' ).insertAfter( jQuery( '#home-description' ).closest( 'tr' ) );
</script> <?php
}
``` |
243,811 | <p>I want to update multiple rows in one query using wpdb->update. I get no error in the <a href="https://codex.wordpress.org/Debugging_in_WordPress#WP_DEBUG_LOG" rel="nofollow">debug.log</a> file but only the last row is updated.</p>
<pre><code>$my_update = $wpdb->update( $wpdb->prefix . 'my_settings',
array( 'value' => $tmp_mail_smtp,
'value' => $tmp_mail_smtp_host,
'value' => $tmp_mail_smtp_auth ),
array( 'name' => 'mail-smtp',
'name' => 'mail-smtp-host',
'name' => 'mail-smtp-auth' ) );
</code></pre>
<p>The table structure is (eg):</p>
<pre><code>id - name - value
1 - mail-smtp - yes
2 - mail-smtp-host - smtp.domain.tld
3 - mail-smtp-auth - yes
</code></pre>
<p>I want to update the <code>value</code> at <code>name</code>. Am i doing something wrong?</p>
<p><strong>Update:</strong></p>
<p>With <code>$wpdb->last_query;</code> i get <code>UPDATE settings SET value = 0 WHERE name = mail-smtp-auth</code> It seems like he not even recognize the other. <code>$wpdb->last_result</code> and <code>$wpdb->last_error</code> are both empty.</p>
| [
{
"answer_id": 243825,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 0,
"selected": false,
"text": "<p>Your syntax looks okay. My guess is your first two variables are empty. </p>\n\n<p>Try hardcoding in values to ... | 2016/10/24 | [
"https://wordpress.stackexchange.com/questions/243811",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54551/"
] | I want to update multiple rows in one query using wpdb->update. I get no error in the [debug.log](https://codex.wordpress.org/Debugging_in_WordPress#WP_DEBUG_LOG) file but only the last row is updated.
```
$my_update = $wpdb->update( $wpdb->prefix . 'my_settings',
array( 'value' => $tmp_mail_smtp,
'value' => $tmp_mail_smtp_host,
'value' => $tmp_mail_smtp_auth ),
array( 'name' => 'mail-smtp',
'name' => 'mail-smtp-host',
'name' => 'mail-smtp-auth' ) );
```
The table structure is (eg):
```
id - name - value
1 - mail-smtp - yes
2 - mail-smtp-host - smtp.domain.tld
3 - mail-smtp-auth - yes
```
I want to update the `value` at `name`. Am i doing something wrong?
**Update:**
With `$wpdb->last_query;` i get `UPDATE settings SET value = 0 WHERE name = mail-smtp-auth` It seems like he not even recognize the other. `$wpdb->last_result` and `$wpdb->last_error` are both empty. | I googled a lot the last days and a few times i´ve seen postings that say that the `$wpdb->update` function doens´t support multiple updates and that this is not well documented. -> Sorry i don´t have links anymore...
I think that this is true because i couldn´t get it to work and i found not a single example witch works this way. So i use this way now to update multiple rows and still be able to handle errors.
The function:
```
function update_queries( $queries ) {
global $wpdb;
// set array
$error = array();
// run update commands
foreach( $queries as $query ) {
$query = str_replace( '[wp-prefix]', $wpdb->prefix, $query );
$last_error = $wpdb->last_error;
$wpdb->query( $query );
// fill array when we have an error
if( (empty( $wpdb->result ) || !$wpdb->result ) && !empty( $wpdb->last_error ) && $last_error != $wpdb->last_error ) {
$error[]= $wpdb->last_error." ($query)";
}
}
// when we have an error
if( $error ) {
return $error;
// when everything is fine
}else{
return false;
}
}
```
If we want to update a few things:
```
// update database
$queries = array();
$queries[] = "UPDATE `[wp-prefix]table` SET `value` = '$value' WHERE `name` = 'name';";
$queries[] = "UPDATE `[wp-prefix]table` SET `value` = '$value2' WHERE `name` = 'name2';";
$error = update_queries( $queries );
// if we have an error
if( !empty( $error ) ) {
.....
// when everything is fine
}else{
.....
}
``` |
243,819 | <p>I'm creating a wordpress theme for a client to use in his existent wordpress site. Anyways, I've completed the theme except one specific thing. I see that he has lots of pages with the keyword Module in the title. Example of the title would be "How to create this product: Module 1." In his previous theme, they had a wordpress page template - page-module.php use specifically for these pages. However, I created a wp page template in my theme with the same name but when I go to any of these pages, it is displaying the default page.php template instead of the page-module.php template. When I switch back to his theme, it work fine with his page-module.php template but when I switch by to my theme, it doesn't work. Can someone please help me understand why it's not working with my theme?</p>
| [
{
"answer_id": 243825,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 0,
"selected": false,
"text": "<p>Your syntax looks okay. My guess is your first two variables are empty. </p>\n\n<p>Try hardcoding in values to ... | 2016/10/24 | [
"https://wordpress.stackexchange.com/questions/243819",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105584/"
] | I'm creating a wordpress theme for a client to use in his existent wordpress site. Anyways, I've completed the theme except one specific thing. I see that he has lots of pages with the keyword Module in the title. Example of the title would be "How to create this product: Module 1." In his previous theme, they had a wordpress page template - page-module.php use specifically for these pages. However, I created a wp page template in my theme with the same name but when I go to any of these pages, it is displaying the default page.php template instead of the page-module.php template. When I switch back to his theme, it work fine with his page-module.php template but when I switch by to my theme, it doesn't work. Can someone please help me understand why it's not working with my theme? | I googled a lot the last days and a few times i´ve seen postings that say that the `$wpdb->update` function doens´t support multiple updates and that this is not well documented. -> Sorry i don´t have links anymore...
I think that this is true because i couldn´t get it to work and i found not a single example witch works this way. So i use this way now to update multiple rows and still be able to handle errors.
The function:
```
function update_queries( $queries ) {
global $wpdb;
// set array
$error = array();
// run update commands
foreach( $queries as $query ) {
$query = str_replace( '[wp-prefix]', $wpdb->prefix, $query );
$last_error = $wpdb->last_error;
$wpdb->query( $query );
// fill array when we have an error
if( (empty( $wpdb->result ) || !$wpdb->result ) && !empty( $wpdb->last_error ) && $last_error != $wpdb->last_error ) {
$error[]= $wpdb->last_error." ($query)";
}
}
// when we have an error
if( $error ) {
return $error;
// when everything is fine
}else{
return false;
}
}
```
If we want to update a few things:
```
// update database
$queries = array();
$queries[] = "UPDATE `[wp-prefix]table` SET `value` = '$value' WHERE `name` = 'name';";
$queries[] = "UPDATE `[wp-prefix]table` SET `value` = '$value2' WHERE `name` = 'name2';";
$error = update_queries( $queries );
// if we have an error
if( !empty( $error ) ) {
.....
// when everything is fine
}else{
.....
}
``` |
243,839 | <p>I put my timezone in <strong>America/Lima</strong> ( Setting > General )</p>
<p>But <strong>current_time('timestamp')</strong> show other datetime.</p>
<p>For example:
Now in Lima it is 2015-10-25 12:01:00 but current_time('timestamp') says : 2016-10-24 19:01:05</p>
<p>Something am I doing wrong?</p>
<p>PD: My variables in wp_option are:
<strong>gmt_offset</strong> is empty,
<strong>timezone_string</strong> is America/Lima</p>
<p>Regards</p>
| [
{
"answer_id": 243825,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 0,
"selected": false,
"text": "<p>Your syntax looks okay. My guess is your first two variables are empty. </p>\n\n<p>Try hardcoding in values to ... | 2016/10/25 | [
"https://wordpress.stackexchange.com/questions/243839",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27785/"
] | I put my timezone in **America/Lima** ( Setting > General )
But **current\_time('timestamp')** show other datetime.
For example:
Now in Lima it is 2015-10-25 12:01:00 but current\_time('timestamp') says : 2016-10-24 19:01:05
Something am I doing wrong?
PD: My variables in wp\_option are:
**gmt\_offset** is empty,
**timezone\_string** is America/Lima
Regards | I googled a lot the last days and a few times i´ve seen postings that say that the `$wpdb->update` function doens´t support multiple updates and that this is not well documented. -> Sorry i don´t have links anymore...
I think that this is true because i couldn´t get it to work and i found not a single example witch works this way. So i use this way now to update multiple rows and still be able to handle errors.
The function:
```
function update_queries( $queries ) {
global $wpdb;
// set array
$error = array();
// run update commands
foreach( $queries as $query ) {
$query = str_replace( '[wp-prefix]', $wpdb->prefix, $query );
$last_error = $wpdb->last_error;
$wpdb->query( $query );
// fill array when we have an error
if( (empty( $wpdb->result ) || !$wpdb->result ) && !empty( $wpdb->last_error ) && $last_error != $wpdb->last_error ) {
$error[]= $wpdb->last_error." ($query)";
}
}
// when we have an error
if( $error ) {
return $error;
// when everything is fine
}else{
return false;
}
}
```
If we want to update a few things:
```
// update database
$queries = array();
$queries[] = "UPDATE `[wp-prefix]table` SET `value` = '$value' WHERE `name` = 'name';";
$queries[] = "UPDATE `[wp-prefix]table` SET `value` = '$value2' WHERE `name` = 'name2';";
$error = update_queries( $queries );
// if we have an error
if( !empty( $error ) ) {
.....
// when everything is fine
}else{
.....
}
``` |
243,851 | <p>I just created a child theme and activated it.But when I visit the page,it's completely blank.</p>
<p>In the display is the themes folder where I have my parent theme and the child,then below is the site details from the parent style.css which I simply copied and pasted to the child stylesheet.</p>
<p><a href="https://i.stack.imgur.com/yY5uE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yY5uE.png" alt="enter image description here"></a></p>
<p>functions.php looks like this:</p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
</code></pre>
<p>As the photo shows,the theme is active.</p>
<p><a href="https://i.stack.imgur.com/4ArRw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4ArRw.png" alt="enter image description here"></a></p>
<p>How can I create a child theme and make it visible as the parent theme?</p>
<p>This is what I see when I load the page and try to inspect:</p>
<p><a href="https://i.stack.imgur.com/QCSfx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QCSfx.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 243855,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": false,
"text": "<p>I think you've nothing in the <code>index.php</code> file. So what is happening that the child theme is ca... | 2016/10/25 | [
"https://wordpress.stackexchange.com/questions/243851",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99178/"
] | I just created a child theme and activated it.But when I visit the page,it's completely blank.
In the display is the themes folder where I have my parent theme and the child,then below is the site details from the parent style.css which I simply copied and pasted to the child stylesheet.
[](https://i.stack.imgur.com/yY5uE.png)
functions.php looks like this:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
```
As the photo shows,the theme is active.
[](https://i.stack.imgur.com/4ArRw.png)
How can I create a child theme and make it visible as the parent theme?
This is what I see when I load the page and try to inspect:
[](https://i.stack.imgur.com/QCSfx.png) | I think you've nothing in the `index.php` file. So what is happening that the child theme is calling the child theme's `index.php` over parent theme's `index.php`. And you have nothing on `index.php`. So the site is showing nothing. Delete the child theme's `index.php`. You'll see the site live. |
243,856 | <p>Hello I'm in a bit of a trouble. I don't know what's wrong with what I'm doing. I want to add class to current category. So my php looks like this:</p>
<pre><code> <menu id="nav">
<ul>
<?php $cat_id = get_cat_ID();
foreach( $categories as $c ):?>
<li class="<?php if(($c->term_id) == $cat_id){echo 'active' ;} ?>">
<a href="<?php echo get_category_link( $c->term_id ); ?>" title="<?php echo $c->cat_name ;?>">
<?php echo $c->cat_name ;?>
</a>
</li>
<?php endforeach; ?>
</ul>
</menu>
</code></pre>
<p>I just want to add active class to the current category. But this is not working.</p>
| [
{
"answer_id": 243858,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 2,
"selected": true,
"text": "<p>You can use <code>get_queried_object()</code>, which will return category object.</p>\n\n<p>See doc... | 2016/10/25 | [
"https://wordpress.stackexchange.com/questions/243856",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105264/"
] | Hello I'm in a bit of a trouble. I don't know what's wrong with what I'm doing. I want to add class to current category. So my php looks like this:
```
<menu id="nav">
<ul>
<?php $cat_id = get_cat_ID();
foreach( $categories as $c ):?>
<li class="<?php if(($c->term_id) == $cat_id){echo 'active' ;} ?>">
<a href="<?php echo get_category_link( $c->term_id ); ?>" title="<?php echo $c->cat_name ;?>">
<?php echo $c->cat_name ;?>
</a>
</li>
<?php endforeach; ?>
</ul>
</menu>
```
I just want to add active class to the current category. But this is not working. | You can use `get_queried_object()`, which will return category object.
See documentation:
<https://codex.wordpress.org/Function_Reference/get_queried_object> |
243,877 | <p>I have written this function for loggin user out. The user is loggin out but not redirecting to the page instead goes to home page which default logout Url. i have tried wp_logout_url() and also wp_redirect().</p>
<pre><code>function wc_registration_redirect( $redirect_to) {
wp_logout();
wp_redirect( '/my-account');
exit;
}
</code></pre>
| [
{
"answer_id": 243878,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>You need to hook it to <code>wp_logout</code> actions hook and remove the <code>wp_logout();</code> from t... | 2016/10/25 | [
"https://wordpress.stackexchange.com/questions/243877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105617/"
] | I have written this function for loggin user out. The user is loggin out but not redirecting to the page instead goes to home page which default logout Url. i have tried wp\_logout\_url() and also wp\_redirect().
```
function wc_registration_redirect( $redirect_to) {
wp_logout();
wp_redirect( '/my-account');
exit;
}
``` | The correct method for changing the logout redirect is the `logout_redirect` filter:
```
/**
* Filters the log out redirect URL.
*
* @since 4.2.0
*
* @param string $redirect_to The redirect destination URL.
* @param string $requested_redirect_to The requested redirect destination URL passed as a parameter.
* @param WP_User $user The WP_User object for the user that's logging out.
*/
add_filter( 'logout_redirect', function( $redirect_to, $requested_redirect_to, $user ) {
if ( ! $requested_redirect_to ) { // Don't override the redirect if one was already set in the logout URL
$redirect = home_url( user_trailingslashit( 'my-account' ) );
}
return $redirect;
}, 10, 3 );
``` |
243,882 | <p>I'm building a WordPress website that will have around 50 smaller sites in it; <em>either a state with each county being the smaller site</em>.</p>
<p>Each site will be managed by a different person.</p>
<p>I've just started with multisite and was wondering if this is the best way to go or if there is a better way to do this.</p>
| [
{
"answer_id": 243878,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>You need to hook it to <code>wp_logout</code> actions hook and remove the <code>wp_logout();</code> from t... | 2016/10/25 | [
"https://wordpress.stackexchange.com/questions/243882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105621/"
] | I'm building a WordPress website that will have around 50 smaller sites in it; *either a state with each county being the smaller site*.
Each site will be managed by a different person.
I've just started with multisite and was wondering if this is the best way to go or if there is a better way to do this. | The correct method for changing the logout redirect is the `logout_redirect` filter:
```
/**
* Filters the log out redirect URL.
*
* @since 4.2.0
*
* @param string $redirect_to The redirect destination URL.
* @param string $requested_redirect_to The requested redirect destination URL passed as a parameter.
* @param WP_User $user The WP_User object for the user that's logging out.
*/
add_filter( 'logout_redirect', function( $redirect_to, $requested_redirect_to, $user ) {
if ( ! $requested_redirect_to ) { // Don't override the redirect if one was already set in the logout URL
$redirect = home_url( user_trailingslashit( 'my-account' ) );
}
return $redirect;
}, 10, 3 );
``` |
243,883 | <p>so, I've encountered on a problem. </p>
<p>What i want?</p>
<ul>
<li>I want that my search finds any text on the page</li>
</ul>
<p>What is the problem?</p>
<ul>
<li>Search is only for posts / media / pages. I have one plugin in which I've stored some data and that data is visible on the page, and I want to be able to search that data.</li>
</ul>
<p>What did I tried?</p>
<ul>
<li>I tried to change the search querries (<code>select * from wp_posts</code>) to something that I wanted, nothing happened</li>
<li>Tried around 15 plugins with search, nothing happened</li>
</ul>
<p>So, my question is this:</p>
<p>How can I search within a wordpress page, so my search finds ANY text on the page?</p>
<p>NOTICE:</p>
<p>text is not stored in wp_posts table nor there is a posts. Only page with shortcode.</p>
<p>Thanks!</p>
| [
{
"answer_id": 243901,
"author": "Christopher Corrales",
"author_id": 105589,
"author_profile": "https://wordpress.stackexchange.com/users/105589",
"pm_score": 0,
"selected": false,
"text": "<p>WP default search is not good, try this plugin: <a href=\"https://wordpress.org/plugins/search... | 2016/10/25 | [
"https://wordpress.stackexchange.com/questions/243883",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89803/"
] | so, I've encountered on a problem.
What i want?
* I want that my search finds any text on the page
What is the problem?
* Search is only for posts / media / pages. I have one plugin in which I've stored some data and that data is visible on the page, and I want to be able to search that data.
What did I tried?
* I tried to change the search querries (`select * from wp_posts`) to something that I wanted, nothing happened
* Tried around 15 plugins with search, nothing happened
So, my question is this:
How can I search within a wordpress page, so my search finds ANY text on the page?
NOTICE:
text is not stored in wp\_posts table nor there is a posts. Only page with shortcode.
Thanks! | Use [mark.js](https://markjs.io/), a jQuery plugin
==================================================
[mark.js](https://markjs.io/) is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:
* search for keywords separately instead of the complete term
* map diacritics (For example if "justo" should also match "justò")
* ignore matches inside custom elements
* use custom highlighting element
* use custom highlighting class
* map custom synonyms
* search also inside iframes
* receive not found terms
**[DEMO](https://markjs.io/configurator.html)**
Alternatively you can see [this fiddle](https://jsfiddle.net/julmot/vpav6tL1/).
**Usage example**:
```
// Highlight "keyword" in the specified context
$(".context").mark("keyword");
// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);
```
It's free and developed open-source on GitHub ([project reference](https://github.com/julmot/mark.js)).
Example of mark.js keyword highlighting with your code
======================================================
```js
$(function() {
$("input").on("input.highlight", function() {
// Determine specified search term
var searchTerm = $(this).val();
// Highlight search term inside a specific context
$("#context").unmark().mark(searchTerm);
}).trigger("input.highlight").focus();
});
```
```css
mark {
background: orange;
color: black;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/mark.js/7.0.0/jquery.mark.min.js"></script>
<input type="text" value="test">
<div id="context">
Lorem ipsum dolor test sit amet
</div>
```
I found the answer [here](https://stackoverflow.com/questions/10011385/jquery-search-in-static-html-page-with-highlighting-of-found-word). You can find plenty of other answer there also. But I prefer to use a `jQuery` plugin. The reason is given below-
Why using a selfmade highlighting function is a bad idea
========================================================
The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:
* You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. `innerHTML`)
* If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
* You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!
Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.
When using an existing, well implemented plugin, you don't have to worry about above named things.
Hope that thing helps you. |
243,888 | <p>I believe Jetpack is using "Font Awesome" to display social icons.
This is the css <code>content: "\f203";</code> to display facebook for example. If I look in the site source I can't find anywhere the "Font Awesome" being downloaded.</p>
<p>How does this works? </p>
<p>The thing is that I just want to use those icons in my header without making the user download the font again. If I use <code>content: "\f203";</code> in my style.css the icon doesn't show.</p>
<p>I have Jetpack active and social icons are displayed on each post.</p>
| [
{
"answer_id": 243894,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to rely on Jetpack for font awesome you need to have the CSS files loaded. Best way (in my opi... | 2016/10/25 | [
"https://wordpress.stackexchange.com/questions/243888",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104433/"
] | I believe Jetpack is using "Font Awesome" to display social icons.
This is the css `content: "\f203";` to display facebook for example. If I look in the site source I can't find anywhere the "Font Awesome" being downloaded.
How does this works?
The thing is that I just want to use those icons in my header without making the user download the font again. If I use `content: "\f203";` in my style.css the icon doesn't show.
I have Jetpack active and social icons are displayed on each post. | If you don't want to rely on Jetpack for font awesome you need to have the CSS files loaded. Best way (in my opinion) to do this is via the CDN.
I use the following:
```
// Add font awesome & bootstrap
function awesome_css() {
wp_enqueue_style("fontawesome", 'https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css');
wp_enqueue_style("bootstrap3", 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
}
add_action( 'wp_enqueue_scripts', 'awesome_css' );
```
This goes into your functions.php file.
Then you have a few choices of how to add it. You can use the method you've referred to, or you can use the [fontawesome cheat sheet](http://fontawesome.io/cheatsheet/)
Refer to the examples on fontawesome for more info. |
243,912 | <p>I have a custom post type <code>acme_reviews</code>. I've namespaced it as suggested in tutorials to prevent future conflicts. But I want its archive page to simply be <code>acme.com/reviews</code>, not <code>acme.com/acme_reviews</code>. How do I achieve this? This is my code:</p>
<pre><code>function create_reviews_post_type() {
register_post_type('acme_reviews', array(
'labels' => array(
'name' => __('Reviews'),
'singular_name' => __('Review')
),
'menu_position' => 5,
'public' => true,
'has_archive' => true,
)
);
}
add_action('init', 'create_reviews_post_type');
</code></pre>
| [
{
"answer_id": 243913,
"author": "Fencer04",
"author_id": 98527,
"author_profile": "https://wordpress.stackexchange.com/users/98527",
"pm_score": 3,
"selected": true,
"text": "<p>The register_post_type has_archive option also accepts a string. That string will be used for the archives. S... | 2016/10/25 | [
"https://wordpress.stackexchange.com/questions/243912",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105495/"
] | I have a custom post type `acme_reviews`. I've namespaced it as suggested in tutorials to prevent future conflicts. But I want its archive page to simply be `acme.com/reviews`, not `acme.com/acme_reviews`. How do I achieve this? This is my code:
```
function create_reviews_post_type() {
register_post_type('acme_reviews', array(
'labels' => array(
'name' => __('Reviews'),
'singular_name' => __('Review')
),
'menu_position' => 5,
'public' => true,
'has_archive' => true,
)
);
}
add_action('init', 'create_reviews_post_type');
``` | The register\_post\_type has\_archive option also accepts a string. That string will be used for the archives. See the changes in the code below:
```
function create_reviews_post_type() {
register_post_type('acme_reviews', array(
'labels' => array(
'name' => __('Reviews'),
'singular_name' => __('Review')
),
'menu_position' => 5,
'public' => true,
'has_archive' => 'reviews',
);
}
add_action('init', 'create_reviews_post_type');
``` |
243,925 | <p>i am trying to add re-order for user panel in wordpress. I tried to intall some plugin called post re-order but did not work out for user panel. plz suggest me with the best idea.</p>
<p>thx
<a href="https://i.stack.imgur.com/E8JxI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E8JxI.png" alt="enter image description here" /></a>
screenshot of wp backend panel</p>
| [
{
"answer_id": 243963,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 0,
"selected": false,
"text": "<p>You can use an Admin Menu order plugin. There are several, <a href=\"https://wordpress.org/plugins/admin-menu-e... | 2016/10/25 | [
"https://wordpress.stackexchange.com/questions/243925",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105644/"
] | i am trying to add re-order for user panel in wordpress. I tried to intall some plugin called post re-order but did not work out for user panel. plz suggest me with the best idea.
thx
[](https://i.stack.imgur.com/E8JxI.png)
screenshot of wp backend panel | You can re order admin left menu by below code:
```
/*
* Code below groups Dashboard/Posts/Pages/Comments together at the top of the dashboard menu.
* If you were to have a custom type that you want to add to the group use the following edit.php?post_type=YOURPOSTTYPENAME
*/
function reorder_my_admin_menu( $__return_true ) {
return array(
'index.php', // Dashboard
'edit.php?post_type=page', // Pages
'edit.php', // Posts
'upload.php', // Media
'themes.php', // Appearance
'separator1', // --Space--
'edit-comments.php', // Comments
'users.php', // Users
'separator2', // --Space--
'plugins.php', // Plugins
'tools.php', // Tools
'options-general.php', // Settings
);
}
add_filter( 'custom_menu_order', 'reorder_my_admin_menu' );
add_filter( 'menu_order', 'reorder_my_admin_menu' );
```
Above code used [custom\_menu\_order](https://codex.wordpress.org/Plugin_API/Filter_Reference/custom_menu_order) and [menu\_order](https://codex.wordpress.org/Plugin_API/Filter_Reference/menu_order) hook to re order existing menu items. Hope this help you well! |