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.php#L541\" rel=\"nofollow\">no hook</a> to change the HTML of the input (only the <code>enter_title_here</code> filter to change the placeholder text). You could pull this off easily with jQuery, though. Try this in your functionality plugin or theme's <code>functions.php</code> file:</p>\n\n<pre><code>// Add to the new post screen for any post type\nadd_action( 'admin_footer-post-new.php', 'wpse_add_required_attr_to_title_field' );\n\n// Add to the post edit screen for any post type\nadd_action( 'admin_footer-post.php', 'wpse_add_required_attr_to_title_field' );\n\nfunction wpse_add_required_attr_to_title_field() {\n ?>\n <script>\n jQuery(document).ready(function($){\n $('input[name=post_title]').prop('required',true);\n });\n </script>\n <?php\n}\n</code></pre>\n\n<p>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 <a href=\"http://caniuse.com/#feat=form-validation\" rel=\"nofollow\">isn't implemented exactly the same across the board</a>, 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 <a href=\"https://wordpress.org/plugins/force-post-title/\" rel=\"nofollow\">Force Post Title</a> plugin.</p>\n"
},
{
"answer_id": 243715,
"author": "mike23",
"author_id": 1381,
"author_profile": "https://wordpress.stackexchange.com/users/1381",
"pm_score": 1,
"selected": false,
"text": "<p>As brianjohnhanna points out there is no hook to change the HTML of the title field, so the closest possible answer is to do jQuery validation.</p>\n\n<p>Here's what I ended up doing, create a plugin with :</p>\n\n<pre><code>function wpse_242302_mandatory_title( $hook ) {\n\n global $post;\n\n if ( $hook == 'post-new.php' || $hook == 'post.php' ) {\n\n wp_enqueue_script( 'mandatory-title', plugins_url( 'mandatory-title.js', __FILE__ ), array( 'jquery' ) );\n\n }\n}\nadd_action( 'admin_enqueue_scripts', 'wpse_242302_mandatory_title', 20, 1 );\n</code></pre>\n\n<p>and the javascript :</p>\n\n<pre><code>$(document).ready(function() {\n\n $('#post').submit(function(){\n\n if( !$('input[name=post_title]').val() ) {\n\n $( '.wrap > h1').after('<div id=\"message\" class=\"error\"><p>Please enter a title.</p></div>' );\n\n return false;\n\n }\n\n });\n\n});\n</code></pre>\n\n<p>Instead of adding the \"required\" attribute it displays a default Wordpress error message, I thought this integrated better with the admin.</p>\n"
}
] |
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, a checkbox in the page would be nice, which if checked will hide the editor.</p>\n\n<p>For more info > <a href=\"https://codex.wordpress.org/Function_Reference/remove_post_type_support\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/remove_post_type_support</a></p>\n"
},
{
"answer_id": 242371,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 3,
"selected": true,
"text": "<p>I hope I understood your question right.</p>\n\n<p>The following code will remove the editor from the pages using particular templates:</p>\n\n<pre><code><?php\n\nfunction wpse242371_remove_editor_from_some_pages()\n{\n global $post;\n\n if( ! is_a($post, 'WP_Post') ) {\n return;\n }\n\n\n /* basename is used for templates that are in the subdirectory of the theme */\n $current_page_template_slug = basename( get_page_template_slug($post_id) );\n\n /* file names of templates to remove the editor on */\n $excluded_template_slugs = array(\n 'tmp_file_one.php',\n 'tmp_file_two.php',\n 'tmp_file_three.php'\n );\n\n if( in_array($current_page_template_slug, $excluded_template_slugs) ) {\n /* remove editor from pages */\n remove_post_type_support('page', 'editor');\n /* if needed, add posts or CPTs to remove the editor on */\n // remove_post_type_support('post', 'editor');\n // remove_post_type_support('movies', 'editor');\n }\n\n}\n\nadd_action('admin_enqueue_scripts', 'wpse242371_remove_editor_from_some_pages');\n</code></pre>\n"
}
] |
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(){\n$labels = array(\n 'name' =>_x( 'Insurance all category', 'taxonomy general name' ),\n 'singular_name' => _x( 'Category', 'taxonomy singular name' ),\n 'search_items' => __( 'Search Category' ),\n 'all_items' => __( 'All Categories' ),\n 'parent_item' => __( 'Parent Category' ),\n 'parent_item_colon' => __( 'Parent Category:' ),\n 'edit_item' => __( 'Edit Category' ),\n 'update_item' => __( 'Update Category' ),\n 'add_new_item' => __( 'Add New Category' ),\n 'new_item_name' => __( 'New Category' ),\n 'menu_name' => __( 'Categories' ),\n\n);\n\nregister_taxonomy('insurnce_all_categories', array('insurance_all'),$args);}add_action('init','insurance_all_category');?>\n</code></pre>\n\n<p>and needs to be this:</p>\n\n<pre><code>function insurance_all_category(){\n$labels = array(\n 'name' =>_x( 'Insurance all category', 'taxonomy general name' ),\n 'singular_name' => _x( 'Category', 'taxonomy singular name' ),\n 'search_items' => __( 'Search Category' ),\n 'all_items' => __( 'All Categories' ),\n 'parent_item' => __( 'Parent Category' ),\n 'parent_item_colon' => __( 'Parent Category:' ),\n 'edit_item' => __( 'Edit Category' ),\n 'update_item' => __( 'Update Category' ),\n 'add_new_item' => __( 'Add New Category' ),\n 'new_item_name' => __( 'New Category' ),\n 'menu_name' => __( 'Categories' ),\n\n);\n\n//new code\n$args = array(\n 'labels' => $labels\n);\n\nregister_taxonomy('insurnce_all_categories', array('insurance_all'),$args);}add_action('init','insurance_all_category');?>\n</code></pre>\n"
},
{
"answer_id": 261386,
"author": "Joydev Pal",
"author_id": 59561,
"author_profile": "https://wordpress.stackexchange.com/users/59561",
"pm_score": 0,
"selected": false,
"text": "<p>I faced the same problem in my theme. </p>\n\n<p>Remove extra whitespace in php tag. It may be in php closing tag in functions.php file or any included file. </p>\n\n<p>If you can not find extra whitespace, make a fresh new file and rewrite the code.</p>\n\n<p>Thank you.</p>\n"
},
{
"answer_id": 301231,
"author": "Vivekpathak",
"author_id": 135442,
"author_profile": "https://wordpress.stackexchange.com/users/135442",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function insurance_all_category() {\n $labels = array(\n 'name' => _x( 'Insurance all category', 'taxonomy general name' ),\n 'singular_name' => _x( 'Category', 'taxonomy singular name' ),\n 'search_items' => __( 'Search Category' ),\n 'all_items' => __( 'All Categories' ),\n 'parent_item' => __( 'Parent Category' ),\n 'parent_item_colon' => __( 'Parent Category:' ),\n 'edit_item' => __( 'Edit Category' ),\n 'update_item' => __( 'Update Category' ),\n 'add_new_item' => __( 'Add New Category' ),\n 'new_item_name' => __( 'New Category' ),\n 'menu_name' => __( 'Categories' ),\n );\n\n\n $args = array(\n\n'hierarchical' => true,\n'labels' => $labels,\n'show_ui' => true,\n'show_admin_column' => true,\n'query_var' => true,\n'rewrite' => array('slug' => 'category' )\n\n);\n\n register_taxonomy('insurnce_all_categories', array('insurance_all'),$args);\n}\n\nadd_action('init','insurance_all_category');\n</code></pre>\n\n<p>Try this code.</p>\n"
}
] |
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\"><code>wp_head</code></a> action in admin area is <a href=\"https://developer.wordpress.org/reference/hooks/admin_head/\" rel=\"noreferrer\"><code>admin_head</code></a>. But, if your CSS depends on another stylesheet, you should use <a href=\"https://codex.wordpress.org/Function_Reference/wp_add_inline_style\" rel=\"noreferrer\"><code>wp_add_inline_style()</code></a> function hooked to <a href=\"https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/\" rel=\"noreferrer\"><code>admin_enqueue_scripts</code> action</a>.</p>\n"
},
{
"answer_id": 242417,
"author": "Stephen",
"author_id": 85776,
"author_profile": "https://wordpress.stackexchange.com/users/85776",
"pm_score": 2,
"selected": false,
"text": "<p>You could always just hook into both of them from the same function:-</p>\n\n<pre><code>function wordpress_stackexchange_242372()\n{\n // Your code here\n}\nadd_action( 'wp_head', 'wordpress_stackexchange_242372' );\nadd_action( 'admin_head', 'wordpress_stackexchange_242372' );\n</code></pre>\n\n<p>Pretty sure that should work :)</p>\n"
},
{
"answer_id": 287906,
"author": "Mads Hansen",
"author_id": 116122,
"author_profile": "https://wordpress.stackexchange.com/users/116122",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to <strong>wp_head</strong> and <strong>admin_head</strong> there's a separate hook for the login screen, called <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/login_head\" rel=\"noreferrer\">login_head</a> if any custom code is needed there. </p>\n\n<p><em>( This should have been a comment, but my reputation is still to low. )</em></p>\n"
}
] |
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 putting it in the right place. Check out this similar <a href=\"https://stackoverflow.com/questions/8476654/add-url-rewrite-rule-to-wordpress\">SO</a> thread.</p>\n"
},
{
"answer_id": 242436,
"author": "JADEComputer",
"author_id": 88384,
"author_profile": "https://wordpress.stackexchange.com/users/88384",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks Nick! I thought that would work, and I placed it right after \"RewriteEngine On\" so it came first.</p>\n\n<p>I did find a working solution for handling it though (after 2 hrs):</p>\n\n<pre><code>RewriteRule ^page/(.*)$ /$1 [G]\n</code></pre>\n\n<p>In case anyone else needs to do the same ...</p>\n"
}
] |
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 putting it in the right place. Check out this similar <a href=\"https://stackoverflow.com/questions/8476654/add-url-rewrite-rule-to-wordpress\">SO</a> thread.</p>\n"
},
{
"answer_id": 242436,
"author": "JADEComputer",
"author_id": 88384,
"author_profile": "https://wordpress.stackexchange.com/users/88384",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks Nick! I thought that would work, and I placed it right after \"RewriteEngine On\" so it came first.</p>\n\n<p>I did find a working solution for handling it though (after 2 hrs):</p>\n\n<pre><code>RewriteRule ^page/(.*)$ /$1 [G]\n</code></pre>\n\n<p>In case anyone else needs to do the same ...</p>\n"
}
] |
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 WordPress, $post will be set. So if you just replace <code>get_the_ID()</code> in your function above with <code>$post->ID</code>, it will work. If you've been running other queries on the page, you may need to run <code>wp_reset_query();</code> to get the actual post ID.</p>\n\n<p>If you want to pass a specific post, you need to separate the function from the add_filter call along the lines of:</p>\n\n<pre><code>// function to pass the ID to\nfunction my_meta_excerpt($postID){\n $output=get_post_meta($postID, 'my_meta_field', true);\n return $output;\n}\n// add filter call\nadd_filter( 'get_the_excerpt', my_meta_excerpt);\n</code></pre>\n"
},
{
"answer_id": 242466,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 2,
"selected": false,
"text": "<p>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. </p>\n\n<p>So the function still works in the loop without an explicit post, we make the second argument optional.</p>\n\n<pre><code>add_filter( 'get_the_excerpt', 'wpse_242462_excerpt_filter' );\n\nfunction wpse_242462_excerpt_filter( $excerpt, $post = null ){\n\n if ( $post ) {\n $ID = $post->ID;\n } else {\n $ID = get_the_ID();\n }\n\n $excerpt = get_post_meta( $ID, 'wpse_242462_meta_field', true);\n\n return $excerpt;\n});\n</code></pre>\n\n<p>Hopefully it goes without saying that you need to substitute whatever meta key you are already using.</p>\n"
}
] |
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/Filter_Reference/nav_menu_link_attributes\" rel=\"nofollow\">nav_menu_link_attributes</a>.</p>\n\n<p>So, you can put in your functions.php file something like:</p>\n\n<pre><code>function mysite_add_anchor( $atts, $item, $args ) {\n\n $atts['href'] .= ( !empty( $item->xfn ) ? '#' . $item->xfn : '' );\n\n return $atts;\n\n}\n\nadd_filter( 'nav_menu_link_attributes', 'mysite_add_anchor', 10, 3 );\n</code></pre>\n\n<p>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 #.</p>\n\n<p>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.</p>\n\n<p><a href=\"https://codex.wordpress.org/Appearance_Menus_Screen\" rel=\"nofollow\">https://codex.wordpress.org/Appearance_Menus_Screen</a></p>\n\n<p>Not sure if Link Relationship isn't the right one, but it's the one I use the least.</p>\n\n<p>Note: I didn't test the code.</p>\n"
},
{
"answer_id": 242471,
"author": "Nabil Kadimi",
"author_id": 17187,
"author_profile": "https://wordpress.stackexchange.com/users/17187",
"pm_score": 0,
"selected": false,
"text": "<p>Custom links are the easiest solution, you can always modify the menu when you modify the slug. And yes this can be made into a plugin (or your theme's <code>functions.php</code> file), maybe you could have a checbox on the post/page editing screen that changes the behaviour of the page link so that <code>example.com/some-page</code> would becode <code>example.com/#some-page</code>.</p>\n"
}
] |
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> I've left it here in case it's useful to anyone else and added a second answer for the static front page case.</p>\n\n<p>This will add your custom post type to the home page main loop:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse_242473_add_post_type_to_home' );\n\nfunction wpse_242473_add_post_type_to_home( $query ) {\n\n if( $query->is_main_query() && $query->is_home() ) {\n $query->set( 'post_type', array( 'post', 'your_custom_post_type_here') );\n }\n}\n</code></pre>\n\n<p>Checking <code>is_home</code> makes sure we're on the main blog \"home\" page and <code>is_main_query</code> ensures that we don't inadvertently affect any secondary loops.</p>\n\n<p>If you only want your custom post type and not ordinary posts, then remove <code>post</code> from the array of post types.</p>\n\n<p>There are some incorrect articles on the web which treat this action as a filter. It's not, it passes the query by reference so that you can set query args directly.</p>\n"
},
{
"answer_id": 242574,
"author": "bdtheme",
"author_id": 83330,
"author_profile": "https://wordpress.stackexchange.com/users/83330",
"pm_score": 1,
"selected": false,
"text": "<p>You can follow following steps:<br>\n1)Create a template of your CPT(Custom post type)<br>\n2)Place following codes in that template; replace CPT with your CPT.<br>\n3)Open a new page and publish a new page selecting this template from the right hand side.<br>\n4)Finally, go to setting then click on reading then select front page under A static page.</p>\n\n<p>Codes:</p>\n\n<pre><code><?php\n/**\n *Template Name:CPT\n * @package CPT \n * @since CPT 1.0\n */ \nget_header(); \n\nglobal $paged; \n if( get_query_var( 'paged' ) ) {\n $paged = get_query_var( 'paged' );\n } elseif( get_query_var( 'page' ) ) {\n $paged = get_query_var( 'page' );\n } else {\n $paged = 1;\n }\n\n $args = array(\n 'post_type' => 'CPT',\n 'posts_per_page'=>6,\n 'paged' => $paged,\n );\n\n $query = new WP_Query($args);\n?>\n\n<?php if ( $blog_query->have_posts() ) : ?>\n <?php while ( $query->have_posts() ) : $query->the_post(); ?>\n <div class=\"post-thumbnail\">\n <?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) {?>\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <?php the_post_thumbnail(); ?> \n </a>\n <?php }\n ?>\n </div>\n\n <?php endwhile; ?>\n<?php endif; ?>\n\n<?php get_footer(); ?>\n</code></pre>\n"
},
{
"answer_id": 242641,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": true,
"text": "<p>So if you've registered a CPT called <code>wpse_242473_custom_post_type</code> 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.</p>\n\n<p>It's a modification of some code I use in a lot of sites. Put it in your theme's <code>functions.php</code>. Modify the HTML I've used to suit yourself, of course.</p>\n\n<p>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 <code>[recentposts]</code> into the visual editor on any page, or you can put <code><?php wpse_242473_recent_posts(); ?></code> into any template of your theme.</p>\n\n<p>To put it into the template for your static front page, edit (or create) the template <code>front-page.php</code>. This will be automatically selected for your static front page, without you having to select it within the page edit screen.</p>\n\n<pre><code>function wpse_242473_recent_posts( $atts = null, $content = null, $tag = null ) {\n\n $out = '';\n\n $args = array( \n 'numberposts' => '6', \n 'post_status' => 'publish', \n 'post_type' => 'wpse_242473_custom_post_type' ,\n );\n\n $recent = wp_get_recent_posts( $args );\n\n if ( $recent ) {\n\n $out .= '<section class=\"overview\">';\n\n $out .= '<h1>Recent Projects</h1>';\n\n $out .= '<div class=\"overview\">';\n\n foreach ( $recent as $item ) {\n\n $out .= '<a href=\"' . get_permalink( $item['ID'] ) . '\">';\n $out .= get_the_post_thumbnail( $item['ID'] ); \n $out .= '</a>';\n }\n\n $out .= '</div></section>';\n }\n\n if ( $tag ) {\n return $out;\n } else {\n echo $out;\n }\n\n}\n\nadd_shortcode( 'recentposts', 'wpse_242473_recent_posts' );\n</code></pre>\n\n<p>It's a straightforward retrieval of the posts you want.</p>\n\n<p>The <code>foreach</code> 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.</p>\n\n<p>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.</p>\n"
}
] |
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> I've left it here in case it's useful to anyone else and added a second answer for the static front page case.</p>\n\n<p>This will add your custom post type to the home page main loop:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse_242473_add_post_type_to_home' );\n\nfunction wpse_242473_add_post_type_to_home( $query ) {\n\n if( $query->is_main_query() && $query->is_home() ) {\n $query->set( 'post_type', array( 'post', 'your_custom_post_type_here') );\n }\n}\n</code></pre>\n\n<p>Checking <code>is_home</code> makes sure we're on the main blog \"home\" page and <code>is_main_query</code> ensures that we don't inadvertently affect any secondary loops.</p>\n\n<p>If you only want your custom post type and not ordinary posts, then remove <code>post</code> from the array of post types.</p>\n\n<p>There are some incorrect articles on the web which treat this action as a filter. It's not, it passes the query by reference so that you can set query args directly.</p>\n"
},
{
"answer_id": 242574,
"author": "bdtheme",
"author_id": 83330,
"author_profile": "https://wordpress.stackexchange.com/users/83330",
"pm_score": 1,
"selected": false,
"text": "<p>You can follow following steps:<br>\n1)Create a template of your CPT(Custom post type)<br>\n2)Place following codes in that template; replace CPT with your CPT.<br>\n3)Open a new page and publish a new page selecting this template from the right hand side.<br>\n4)Finally, go to setting then click on reading then select front page under A static page.</p>\n\n<p>Codes:</p>\n\n<pre><code><?php\n/**\n *Template Name:CPT\n * @package CPT \n * @since CPT 1.0\n */ \nget_header(); \n\nglobal $paged; \n if( get_query_var( 'paged' ) ) {\n $paged = get_query_var( 'paged' );\n } elseif( get_query_var( 'page' ) ) {\n $paged = get_query_var( 'page' );\n } else {\n $paged = 1;\n }\n\n $args = array(\n 'post_type' => 'CPT',\n 'posts_per_page'=>6,\n 'paged' => $paged,\n );\n\n $query = new WP_Query($args);\n?>\n\n<?php if ( $blog_query->have_posts() ) : ?>\n <?php while ( $query->have_posts() ) : $query->the_post(); ?>\n <div class=\"post-thumbnail\">\n <?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) {?>\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <?php the_post_thumbnail(); ?> \n </a>\n <?php }\n ?>\n </div>\n\n <?php endwhile; ?>\n<?php endif; ?>\n\n<?php get_footer(); ?>\n</code></pre>\n"
},
{
"answer_id": 242641,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": true,
"text": "<p>So if you've registered a CPT called <code>wpse_242473_custom_post_type</code> 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.</p>\n\n<p>It's a modification of some code I use in a lot of sites. Put it in your theme's <code>functions.php</code>. Modify the HTML I've used to suit yourself, of course.</p>\n\n<p>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 <code>[recentposts]</code> into the visual editor on any page, or you can put <code><?php wpse_242473_recent_posts(); ?></code> into any template of your theme.</p>\n\n<p>To put it into the template for your static front page, edit (or create) the template <code>front-page.php</code>. This will be automatically selected for your static front page, without you having to select it within the page edit screen.</p>\n\n<pre><code>function wpse_242473_recent_posts( $atts = null, $content = null, $tag = null ) {\n\n $out = '';\n\n $args = array( \n 'numberposts' => '6', \n 'post_status' => 'publish', \n 'post_type' => 'wpse_242473_custom_post_type' ,\n );\n\n $recent = wp_get_recent_posts( $args );\n\n if ( $recent ) {\n\n $out .= '<section class=\"overview\">';\n\n $out .= '<h1>Recent Projects</h1>';\n\n $out .= '<div class=\"overview\">';\n\n foreach ( $recent as $item ) {\n\n $out .= '<a href=\"' . get_permalink( $item['ID'] ) . '\">';\n $out .= get_the_post_thumbnail( $item['ID'] ); \n $out .= '</a>';\n }\n\n $out .= '</div></section>';\n }\n\n if ( $tag ) {\n return $out;\n } else {\n echo $out;\n }\n\n}\n\nadd_shortcode( 'recentposts', 'wpse_242473_recent_posts' );\n</code></pre>\n\n<p>It's a straightforward retrieval of the posts you want.</p>\n\n<p>The <code>foreach</code> 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.</p>\n\n<p>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.</p>\n"
}
] |
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> I've left it here in case it's useful to anyone else and added a second answer for the static front page case.</p>\n\n<p>This will add your custom post type to the home page main loop:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse_242473_add_post_type_to_home' );\n\nfunction wpse_242473_add_post_type_to_home( $query ) {\n\n if( $query->is_main_query() && $query->is_home() ) {\n $query->set( 'post_type', array( 'post', 'your_custom_post_type_here') );\n }\n}\n</code></pre>\n\n<p>Checking <code>is_home</code> makes sure we're on the main blog \"home\" page and <code>is_main_query</code> ensures that we don't inadvertently affect any secondary loops.</p>\n\n<p>If you only want your custom post type and not ordinary posts, then remove <code>post</code> from the array of post types.</p>\n\n<p>There are some incorrect articles on the web which treat this action as a filter. It's not, it passes the query by reference so that you can set query args directly.</p>\n"
},
{
"answer_id": 242574,
"author": "bdtheme",
"author_id": 83330,
"author_profile": "https://wordpress.stackexchange.com/users/83330",
"pm_score": 1,
"selected": false,
"text": "<p>You can follow following steps:<br>\n1)Create a template of your CPT(Custom post type)<br>\n2)Place following codes in that template; replace CPT with your CPT.<br>\n3)Open a new page and publish a new page selecting this template from the right hand side.<br>\n4)Finally, go to setting then click on reading then select front page under A static page.</p>\n\n<p>Codes:</p>\n\n<pre><code><?php\n/**\n *Template Name:CPT\n * @package CPT \n * @since CPT 1.0\n */ \nget_header(); \n\nglobal $paged; \n if( get_query_var( 'paged' ) ) {\n $paged = get_query_var( 'paged' );\n } elseif( get_query_var( 'page' ) ) {\n $paged = get_query_var( 'page' );\n } else {\n $paged = 1;\n }\n\n $args = array(\n 'post_type' => 'CPT',\n 'posts_per_page'=>6,\n 'paged' => $paged,\n );\n\n $query = new WP_Query($args);\n?>\n\n<?php if ( $blog_query->have_posts() ) : ?>\n <?php while ( $query->have_posts() ) : $query->the_post(); ?>\n <div class=\"post-thumbnail\">\n <?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) {?>\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <?php the_post_thumbnail(); ?> \n </a>\n <?php }\n ?>\n </div>\n\n <?php endwhile; ?>\n<?php endif; ?>\n\n<?php get_footer(); ?>\n</code></pre>\n"
},
{
"answer_id": 242641,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": true,
"text": "<p>So if you've registered a CPT called <code>wpse_242473_custom_post_type</code> 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.</p>\n\n<p>It's a modification of some code I use in a lot of sites. Put it in your theme's <code>functions.php</code>. Modify the HTML I've used to suit yourself, of course.</p>\n\n<p>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 <code>[recentposts]</code> into the visual editor on any page, or you can put <code><?php wpse_242473_recent_posts(); ?></code> into any template of your theme.</p>\n\n<p>To put it into the template for your static front page, edit (or create) the template <code>front-page.php</code>. This will be automatically selected for your static front page, without you having to select it within the page edit screen.</p>\n\n<pre><code>function wpse_242473_recent_posts( $atts = null, $content = null, $tag = null ) {\n\n $out = '';\n\n $args = array( \n 'numberposts' => '6', \n 'post_status' => 'publish', \n 'post_type' => 'wpse_242473_custom_post_type' ,\n );\n\n $recent = wp_get_recent_posts( $args );\n\n if ( $recent ) {\n\n $out .= '<section class=\"overview\">';\n\n $out .= '<h1>Recent Projects</h1>';\n\n $out .= '<div class=\"overview\">';\n\n foreach ( $recent as $item ) {\n\n $out .= '<a href=\"' . get_permalink( $item['ID'] ) . '\">';\n $out .= get_the_post_thumbnail( $item['ID'] ); \n $out .= '</a>';\n }\n\n $out .= '</div></section>';\n }\n\n if ( $tag ) {\n return $out;\n } else {\n echo $out;\n }\n\n}\n\nadd_shortcode( 'recentposts', 'wpse_242473_recent_posts' );\n</code></pre>\n\n<p>It's a straightforward retrieval of the posts you want.</p>\n\n<p>The <code>foreach</code> 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.</p>\n\n<p>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.</p>\n"
}
] |
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.wordpress.org/Function_Reference/wp_get_post_terms\" rel=\"nofollow\">wp_get_post_terms</a></p>\n\n<pre><code>$terms = wp_get_post_terms( $job->ID, 'job_listing_category' );\n\nforeach ( $terms as $term ) {\n echo $term->name . '<br />';\n}\n</code></pre>\n\n<p>In your case, $taxonomy being 'category'.</p>\n\n<p>This should pull only the taxonomy terms for that post, or in this case, job listing.</p>\n"
},
{
"answer_id": 242539,
"author": "Tex0gen",
"author_id": 97070,
"author_profile": "https://wordpress.stackexchange.com/users/97070",
"pm_score": 2,
"selected": true,
"text": "<p>EDITS:</p>\n\n<pre><code><div id=\"job-manager-job-dashboard\">\n <h3><?php _e( 'Job listings are shown in the table below.', 'wp-job-manager' ); ?></h3>\n <table class=\"job-manager-jobs\">\n <thead>\n <tr>\n <?php foreach ( $job_dashboard_columns as $key => $column ) : ?>\n <th class=\"<?php echo esc_attr( $key ); ?>\"><?php echo esc_html( $column ); ?></th>\n <?php endforeach; ?>\n </tr>\n </thead>\n <tbody>\n <?php if ( ! $jobs ) : ?>\n <tr>\n <td colspan=\"6\"><?php _e( 'You do not have any active listings.', 'wp-job-manager' ); ?></td>\n </tr>\n <?php else : ?>\n <?php foreach ( $jobs as $job ) : ?>\n <tr>\n <?php foreach ( $job_dashboard_columns as $key => $column ) : ?>\n <td class=\"<?php echo esc_attr( $key ); ?>\">\n <?php if ('job_title' === $key ) : ?>\n <?php if ( $job->post_status == 'publish' ) : ?>\n <a href=\"<?php echo get_permalink( $job->ID ); ?>\"><?php echo $job->post_title; ?></a><br> Status: \n\n <br />\n <?php\n\n $terms = wp_get_post_terms( $job->ID, 'job_listing_category' );\n\n foreach ( $terms as $term ) {\n echo $term->name;\n }\n ?>\n\n <?php else : ?>\n\n <?php echo $job->post_title; ?> <small> (<?php the_job_status( $job ); ?>)</small>\n <?php endif; ?>\n <ul class=\"job-dashboard-actions\">\n <?php\n $actions = array();\n\n switch ( $job->post_status ) {\n case 'publish' :\n $actions['edit'] = array( 'label' => __( 'Edit', 'wp-job-manager' ), 'nonce' => false );\n\n\n if ( is_position_filled( $job ) ) {\n $actions['mark_not_filled'] = array( 'label' => __( 'Not filled', 'wp-job-manager' ), 'nonce' => true );\n } else {\n $actions['mark_filled'] = array( 'label' => __( 'Filled', 'wp-job-manager' ), 'nonce' => true );\n }\n\n\n break;\n case 'pending_payment' :\n case 'pending' :\n if ( job_manager_user_can_edit_pending_submissions() ) {\n $actions['edit'] = array( 'label' => __( 'Edit', 'wp-job-manager' ), 'nonce' => false );\n }\n break;\n }\n\n $actions['delete'] = array( 'label' => __( 'Delete', 'wp-job-manager' ), 'nonce' => true );\n $actions = apply_filters( 'job_manager_my_job_actions', $actions, $job );\n\n foreach ( $actions as $action => $value ) {\n $action_url = add_query_arg( array( 'action' => $action, 'job_id' => $job->ID ) );\n if ( $value['nonce'] ) {\n $action_url = wp_nonce_url( $action_url, 'job_manager_my_job_actions' );\n }\n echo '<li><a href=\"' . esc_url( $action_url ) . '\" class=\"job-dashboard-action-' . esc_attr( $action ) . '\">' . esc_html( $value['label'] ) . '</a></li>';\n }\n ?>\n </ul>\n <?php elseif ('date' === $key ) : ?>\n <?php echo date_i18n( get_option( 'date_format' ), strtotime( $job->post_date ) ); ?>\n <?php elseif ('expires' === $key ) : ?>\n <?php echo $job->_job_expires ? date_i18n( get_option( 'date_format' ), strtotime( $job->_job_expires ) ) : '&ndash;'; ?>\n <?php elseif ('filled' === $key ) : ?>\n <?php echo is_position_filled( $job ) ? '&#10004;' : '&ndash;'; ?>\n <?php else : ?>\n <?php do_action( 'job_manager_job_dashboard_column_' . $key, $job ); ?>\n <?php endif; ?>\n </td>\n <?php endforeach; ?>\n </tr>\n <?php endforeach; ?>\n <?php endif; ?>\n </tbody>\n</table>\n<?php get_job_manager_template( 'pagination.php', array( 'max_num_pages' => $max_num_pages ) ); ?>\n</code></pre>\n"
}
] |
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>:</p>\n\n<pre><code><?php\n\n/**\n * Breadcrumbs based on theme's functions\n *\n * @author Nabil Kadimi <[email protected]>\n * @link http://wordpress.stackexchange.com/a/242547/17187\n */\nadd_action( 'init', function() {\n add_shortcode( 'mycrumbs', function() {\n\n /**\n * Start capturing output.\n */\n ob_start();\n\n ?>\n <div class=\"x-breadcrumb-wrap\">\n <div class=\"x-container max width\">\n <?php x_breadcrumbs(); ?>\n <?php if ( is_single() || x_is_portfolio_item() ) : ?>\n <?php x_entry_navigation(); ?>\n <?php endif; ?>\n </div>\n </div>\n <?\n\n /**\n * Stop capturing output and return what was captured to WordPress.\n */\n return ob_get_clean();\n\n } ); // add_shortcode( 'mycrumbs', closure );\n} ); // add_action( 'init', closure );\n</code></pre>\n"
},
{
"answer_id": 242572,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>try this?</p>\n\n<pre><code>function mytest_breadcrumbs() {\n\n$crumbs ='<div class=\"x-breadcrumb-wrap\"><div class=\"x-container max width\">';\n$crumbs.=x_breadcrumbs();\nif ( is_single() || x_is_portfolio_item() ) {\n$crumbs.=x_entry_navigation();\n}\n$crumbs.='</div></div>';\n\n\n // Code\nreturn $crumbs;\n}\nadd_shortcode( 'mycrumbs', 'mytest_breadcrumbs' );\n</code></pre>\n\n<p>then call in page with \n[mycrumbs]</p>\n"
}
] |
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 <[email protected]>
* @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 of extra code I did not need so I removed it and made a concise version just for the webhook integration: <a href=\"https://github.com/amratab/WPStripeWebhook\" rel=\"nofollow noreferrer\">WPStripeWebhook</a>. README is self explanatory. Basically make changes to includes/stripe_listener.php for your events. Also attaching readme here as per stackoverflow guidelines: </p>\n\n<p><strong>Usage:</strong></p>\n\n<ol>\n<li><p>Copy the complete folder WPStripeWebhook in wp-content/plugins. Go\nto website admin page. </p></li>\n<li><p>Activate the WP Stripe webhook plugin for\nplugins section. </p></li>\n<li>After this Settings will start showing Stripe\nwebhook settings section. Click on it. In the page fill the stripe\nkeys and check test mode option if you want to test the plugin. </li>\n<li>In WPStripeWebhook/includes/stripe_listener.php, make changes for your\nevent type and email or whatever you want to do in response to<br>\nan event. It currently sends out an email.</li>\n</ol>\n\n<p><strong>Important notes and suggestions</strong>\nFor live mode, add stripe webhook endpoint (stripe account -> settings -> account settings -> webhook) like this</p>\n\n<blockquote>\n <p>htps://yourdomain.com?webhook-listener=stripe</p>\n</blockquote>\n\n<p>For testing locally on your machine, you can use <a href=\"http://www.ultrahook.com/\" rel=\"nofollow noreferrer\">Ultrahook</a>. Its awesome! Set up your keys and username and start ultrahook on your machine using:</p>\n\n<blockquote>\n <p>ultrahook -k your_ultrahook_key stripe 8888</p>\n</blockquote>\n\n<p>Add a webhook endpoint url in your stripe account similar to this:</p>\n\n<blockquote>\n <p>htp://stripe.your_ultrahook_username.ultrahook.com/your_wp_website_folder_name/stripe-listener.php?webhook-listener=stripe</p>\n</blockquote>\n\n<p>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</p>\n\n<pre><code>define('WP_DEBUG', true); \ndefine( 'WP_DEBUG_LOG', true ); \ndefine('WP_DEBUG_DISPLAY', false ); \n@ini_set( 'display_errors', 0 ); \ndefine('SCRIPT_DEBUG', true );\n</code></pre>\n\n<p>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()</p>\n"
},
{
"answer_id": 263573,
"author": "Yawnolly",
"author_id": 117624,
"author_profile": "https://wordpress.stackexchange.com/users/117624",
"pm_score": 3,
"selected": false,
"text": "<p>For anyone interested. This can also be done fairly easily without a plugin.</p>\n\n<ol>\n<li>First add an endpoint in stripe. <a href=\"https://example.com/payment-failed\" rel=\"noreferrer\">https://example.com/payment-failed</a></li>\n<li>Create a new wordpress page called Payment Failed with the same url.</li>\n<li>In your theme folder, create a new php file called page-payment-failed.php and write all of your webhook response code in here. This file will automatically be run when Stripe tries to access <a href=\"https://example.com/payment-failed\" rel=\"noreferrer\">https://example.com/payment-failed</a>.</li>\n</ol>\n"
},
{
"answer_id": 360493,
"author": "Paul Thomas",
"author_id": 184158,
"author_profile": "https://wordpress.stackexchange.com/users/184158",
"pm_score": 2,
"selected": false,
"text": "<p>A nice clean way of doing is using adding a custom endpoint to wordpress REST API</p>\n\n<p><a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/</a></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function stripe_task() {\n include_once ABSPATH . 'path/to/stripe/autoloader/or/init'; //change\n\n $payload = @file_get_contents('php://input');\n $event = null;\n try {\n $event = \\Stripe\\Event::constructFrom(\n json_decode($payload, true)\n );\n } catch(\\UnexpectedValueException $e) {\n // Invalid payload\n http_response_code(400);\n exit();\n }\n\n // Handle the event\n switch ($event->type) {\n case 'customer.subscription.created':\n // do something!\n break;\n // other type cases you wish to handle\n // ...\n // catch all\n default:\n http_response_code(400);\n exit();\n }\n http_response_code(400);\n} \n\nadd_action('rest_api_init', \n function () {\n register_rest_route( 'stripewebhooks/v1', '/task', array(\n 'methods' => 'POST',\n 'callback' => 'stripe_task',\n 'permission_callback' => function () {\n return true; // security can be done in the handler\n } \n ));\n }\n);\n\n</code></pre>\n\n<p>Then add the endpoint to Stripe</p>\n\n<p>e.g. <code>https://your-site.com/?rest_route=/stripewebhooks/v1/task</code></p>\n\n<p>You can also increase security with signature verification:\n<a href=\"https://stripe.com/docs/webhooks/signatures\" rel=\"nofollow noreferrer\">https://stripe.com/docs/webhooks/signatures</a></p>\n"
}
] |
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 called with the key <code>shoes</code>, you can access it like this</p>\n\n<pre><code>$userObject->shoes\n</code></pre>\n"
},
{
"answer_id": 242579,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 0,
"selected": false,
"text": "<p>This was under the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query#Return_Fields_Parameter\" rel=\"nofollow noreferrer\">return fields parameter on WP_User_Query</a></p>\n<blockquote>\n<p>'all (default) or all_with_meta' - Returns an array of WP_User objects. Must pass an array to subset fields returned.</p>\n<p>*'all_with_meta' currently returns the same fields as 'all' which does not include user fields stored in wp_usermeta. You must create a second query to get the user meta fields by ID or use the __get PHP magic method to get the values of these fields.</p>\n</blockquote>\n<p>So, unless this is outdated, it sounds like it's not directly possible.</p>\n"
}
] |
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 on your way.</p>\n<pre><code>add_action( 'admin_init', 'my_kses_remove_filters' );\nfunction my_kses_remove_filters() {\n $current_user = wp_get_current_user();\n \n if ( my_user_has_role( 'administrator', $current_user ) )\n kses_remove_filters();\n}\n \nfunction my_user_has_role( $role = '', $user = null ) {\n $user = $user ? new WP_User( $user ) : wp_get_current_user();\n \n if ( empty( $user->roles ) )\n return;\n \n if ( in_array( $role, $user->roles ) )\n return true;\n \n return;\n}\n</code></pre>\n<p>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.</p>\n<p>This solutions draws heavily from <a href=\"https://www.thatstevensguy.com/wordpress/wordpress-multisite-unfiltered-html-capability/\" rel=\"nofollow noreferrer\">this page</a>.</p>\n"
},
{
"answer_id": 369499,
"author": "Brett Donald",
"author_id": 143573,
"author_profile": "https://wordpress.stackexchange.com/users/143573",
"pm_score": -1,
"selected": false,
"text": "<p>Adding an action which calls <code>kses_remove_filters()</code> didn't work for me. I actually had to hack WordPress to achieve this.</p>\n<p>The problem is that WordPress has a global override in the method <code>map_meta_cap()</code> in <code>wp-includes/capabilities.php</code>, which ignores the <code>unfiltered_html</code> capability in a multisite install if the user is not a super admin.</p>\n<p>Get rid of that override, and you’re sweet. Until you have to update WordPress, of course, and you’ll have to do it all over again.</p>\n<pre><code> case 'unfiltered_html':\n // Disallow unfiltered_html for all users, even admins and super admins.\n if ( defined( 'DISALLOW_UNFILTERED_HTML' ) && DISALLOW_UNFILTERED_HTML ) {\n $caps[] = 'do_not_allow';\n// } elseif ( is_multisite() && ! is_super_admin( $user_id ) ) {\n// $caps[] = 'do_not_allow';\n } else {\n $caps[] = 'unfiltered_html';\n }\n break;\n</code></pre>\n"
},
{
"answer_id": 406839,
"author": "keetbis",
"author_id": 223213,
"author_profile": "https://wordpress.stackexchange.com/users/223213",
"pm_score": 0,
"selected": false,
"text": "<p>I found this code to work for me</p>\n<pre><code>function multisite_restore_unfiltered_html( $caps, $cap, $user_id, ...$args ) {\n if ( 'unfiltered_html' === $cap && (user_can( $user_id, 'editor' ) || user_can( $user_id, 'administrator' ) ) ) {\n $caps = array( 'unfiltered_html' );\n }\n\n return $caps;\n}\n\nadd_filter( 'map_meta_cap', 'multisite_restore_unfiltered_html', 1, 4 );\n</code></pre>\n<p><a href=\"https://gist.github.com/kellenmace/9e6a6fbb92ec75940f23d2a6f01c9b59\" rel=\"nofollow noreferrer\">https://gist.github.com/kellenmace/9e6a6fbb92ec75940f23d2a6f01c9b59</a></p>\n"
}
] |
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 on your way.</p>\n<pre><code>add_action( 'admin_init', 'my_kses_remove_filters' );\nfunction my_kses_remove_filters() {\n $current_user = wp_get_current_user();\n \n if ( my_user_has_role( 'administrator', $current_user ) )\n kses_remove_filters();\n}\n \nfunction my_user_has_role( $role = '', $user = null ) {\n $user = $user ? new WP_User( $user ) : wp_get_current_user();\n \n if ( empty( $user->roles ) )\n return;\n \n if ( in_array( $role, $user->roles ) )\n return true;\n \n return;\n}\n</code></pre>\n<p>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.</p>\n<p>This solutions draws heavily from <a href=\"https://www.thatstevensguy.com/wordpress/wordpress-multisite-unfiltered-html-capability/\" rel=\"nofollow noreferrer\">this page</a>.</p>\n"
},
{
"answer_id": 369499,
"author": "Brett Donald",
"author_id": 143573,
"author_profile": "https://wordpress.stackexchange.com/users/143573",
"pm_score": -1,
"selected": false,
"text": "<p>Adding an action which calls <code>kses_remove_filters()</code> didn't work for me. I actually had to hack WordPress to achieve this.</p>\n<p>The problem is that WordPress has a global override in the method <code>map_meta_cap()</code> in <code>wp-includes/capabilities.php</code>, which ignores the <code>unfiltered_html</code> capability in a multisite install if the user is not a super admin.</p>\n<p>Get rid of that override, and you’re sweet. Until you have to update WordPress, of course, and you’ll have to do it all over again.</p>\n<pre><code> case 'unfiltered_html':\n // Disallow unfiltered_html for all users, even admins and super admins.\n if ( defined( 'DISALLOW_UNFILTERED_HTML' ) && DISALLOW_UNFILTERED_HTML ) {\n $caps[] = 'do_not_allow';\n// } elseif ( is_multisite() && ! is_super_admin( $user_id ) ) {\n// $caps[] = 'do_not_allow';\n } else {\n $caps[] = 'unfiltered_html';\n }\n break;\n</code></pre>\n"
},
{
"answer_id": 406839,
"author": "keetbis",
"author_id": 223213,
"author_profile": "https://wordpress.stackexchange.com/users/223213",
"pm_score": 0,
"selected": false,
"text": "<p>I found this code to work for me</p>\n<pre><code>function multisite_restore_unfiltered_html( $caps, $cap, $user_id, ...$args ) {\n if ( 'unfiltered_html' === $cap && (user_can( $user_id, 'editor' ) || user_can( $user_id, 'administrator' ) ) ) {\n $caps = array( 'unfiltered_html' );\n }\n\n return $caps;\n}\n\nadd_filter( 'map_meta_cap', 'multisite_restore_unfiltered_html', 1, 4 );\n</code></pre>\n<p><a href=\"https://gist.github.com/kellenmace/9e6a6fbb92ec75940f23d2a6f01c9b59\" rel=\"nofollow noreferrer\">https://gist.github.com/kellenmace/9e6a6fbb92ec75940f23d2a6f01c9b59</a></p>\n"
}
] |
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 you can easily use a plugin. There are multiple ones, free or premium.</p>\n\n<p>I will list \"<strong>Custom Frontend Login Registration Form</strong>\" as I already worked with it in the past. You can reach it on WordPress Repository.</p>\n\n<p><a href=\"https://i.stack.imgur.com/WCAS1.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WCAS1.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>It will generate a shortcode you can use on a custom page for your <strong>Viewer only</strong> users. The plugin also comes with registration shortcode, so will make your visitor's life easier.</p>\n\n<p>Hope this answer your question.</p>\n"
},
{
"answer_id": 242646,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>On-topic answer:</p>\n\n<p>You can just put <code><?php wp_login_form(); ?></code> into any of your theme templates to render a login form on the front end of your site.</p>\n\n<p>Or make your own shortcode <code>[loginform]</code> by putting this into your theme's <code>functions.php</code>:</p>\n\n<pre><code>function wpse_242473_login_form() {\n return wp_login_form( 'echo' => false );\n}\n\nadd_shortcode( 'loginform', 'wpse_242473_login_form' );\n</code></pre>\n"
},
{
"answer_id": 243172,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 0,
"selected": false,
"text": "<p>There is the function <a href=\"https://developer.wordpress.org/reference/functions/wp_login_form/\" rel=\"nofollow\"><code>wp_login_form( [ /* array of arguments */ ] )</code></a>, which displays a login form that you can put into every template. When you look at the internals, you will see that the forms action points to:</p>\n\n<pre><code>esc_url( site_url( 'wp-login.php', 'login_post' ) )\n</code></pre>\n\n<p>…(at least if you did not use the <code>$args['redirect']</code> argument). This means that <code>wp-login.php</code> handles the sign on. Now you have multiple options:</p>\n\n<ol>\n<li><p>You can use the arguments for the function or globally set the filter <code>login_form_defaults</code>, which allows you to alter the default values, like <code>redirect</code>, which per default points to the current site:</p>\n\n<pre><code>( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],\n</code></pre>\n\n<p>Then you can use a filter to redirect based on the role (or perform a log out if the logged in user role did not match the role that you want to allow logging in from this template):</p>\n\n<pre><code> apply_filters( 'login_redirect', $redirect_to, $requested_redirect_to, $user );\n</code></pre></li>\n<li><p>You scratch that idea as you can not determine the difference between an <em>admin</em> and a <em>guest</em> as you do not know the role of a user <em>before</em> they logged in.</p></li>\n</ol>\n"
},
{
"answer_id": 243198,
"author": "davemac",
"author_id": 131,
"author_profile": "https://wordpress.stackexchange.com/users/131",
"pm_score": 0,
"selected": false,
"text": "<p>For a custom register user form, you can use <a href=\"https://www.advancedcustomfields.com/resources/create-a-front-end-form/\" rel=\"nofollow\">Advanced Custom Fields to create a front-end form</a>. </p>\n\n<p>You can set up the custom fields for the registration using ACF, and set the location rules for the field group when User Form is equal to Register, and Add/Edit. </p>\n\n<p>I did something similar, hooking into the <code>acf/pre_save_post</code> filter and doing the following:</p>\n\n<ul>\n<li>sanitize the inputs</li>\n<li>register the user with <code>register_new_user()</code>, which handles the password generation and email notification </li>\n<li>use <code>wp_update_user()</code> and <code>update_user_meta()</code> to map the appropriate custom ACF fields to custom WP user profile fields</li>\n<li>set the new user's role</li>\n<li>use <code>wp_mail()</code> to email admin if required</li>\n</ul>\n\n<p>Some more information on <a href=\"https://support.advancedcustomfields.com/forums/topic/registering-new-user-with-acf/\" rel=\"nofollow\">registering a user with ACF</a> here.</p>\n\n<pre><code>function my_pre_save_user( $post_id ) { \n\n // If we have an email address, add the user\n // This field only exists in the new user field group\n if ( isset($_POST['acf']['add acf_field_ID here']) && !empty($_POST['acf']['add acf_field_ID here'])) {\n\n // sanitize our inputs\n $sanitized_email = sanitize_email( $_POST['acf']['add acf_field_ID here'] );\n $sanitized_firstname = sanitize_text_field( $_POST['acf']['add acf_field_ID here'] );\n $sanitized_lastname = sanitize_text_field( $_POST['acf']['add acf_field_ID here'] );\n $sanitized_contactnumber = sanitize_text_field( $_POST['acf']['add acf_field_ID here'] );\n\n // Prepare basic user info\n $username = $sanitized_email;\n $email = $sanitized_email;\n $display_name = $sanitized_firstname .' '. $sanitized_lastname;\n\n // Register the user and store the ID as $user_id, handles the validation, generates random password and send email notification to user\n $user_id = register_new_user( $username, $email );\n\n // If we get an error (eg user already exists)\n if( is_wp_error( $user_id ) ) {\n // Show the error\n echo 'Error: '.$user_id->get_error_message();\n // Exit\n exit;\n\n // Good to go\n } else {\n\n // get single value from post object\n $dmc_get_company_field = $_POST['acf']['add acf_field_ID here'];\n $dmc_selected_exhibitor = get_field( $dmc_get_company_field );\n\n // Update the new user's info\n wp_update_user( array(\n 'ID' => $user_id,\n 'first_name' => $sanitized_firstname,\n 'last_name' => $sanitized_lastname,\n 'display_name' => $display_name\n ));\n\n // update the new users's meta\n update_user_meta( $user_id, 'dmc_exhibitor_company_name', $dmc_get_company_field );\n update_user_meta( $user_id, 'dmc_exhibitor_contact_number', $sanitized_contactnumber );\n\n // update user role\n $user_id_role = new WP_User( $user_id );\n $user_id_role->set_role( 'contributor' );\n $profile_link = get_edit_user_link( $user_id );\n\n $to = \"[add email addresses here]\";\n $headers[] = 'MIME-Version: 1.0';\n $headers[] = 'Content-Type: text/html; charset=UTF-8';\n $headers[] = 'Reply-To: '. $username. ' <'. $email .'>';\n\n $subject = \"[add email subject here]\";\n $body = \"[add email body here]\";\n\n // send the email\n wp_mail( $to, $subject, $body, $headers );\n\n // redirect to thankyou page\n $redirect_url = get_bloginfo('url') . '[add URL to redirect to here]';\n wp_redirect( $redirect_url );\n\n // exit this script\n exit;\n\n }\n\n } else {\n return $post_id;\n }\n\n}\nadd_filter('acf/pre_save_post' , 'my_pre_save_user' );\n</code></pre>\n"
}
] |
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 you can easily use a plugin. There are multiple ones, free or premium.</p>\n\n<p>I will list \"<strong>Custom Frontend Login Registration Form</strong>\" as I already worked with it in the past. You can reach it on WordPress Repository.</p>\n\n<p><a href=\"https://i.stack.imgur.com/WCAS1.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WCAS1.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>It will generate a shortcode you can use on a custom page for your <strong>Viewer only</strong> users. The plugin also comes with registration shortcode, so will make your visitor's life easier.</p>\n\n<p>Hope this answer your question.</p>\n"
},
{
"answer_id": 242646,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>On-topic answer:</p>\n\n<p>You can just put <code><?php wp_login_form(); ?></code> into any of your theme templates to render a login form on the front end of your site.</p>\n\n<p>Or make your own shortcode <code>[loginform]</code> by putting this into your theme's <code>functions.php</code>:</p>\n\n<pre><code>function wpse_242473_login_form() {\n return wp_login_form( 'echo' => false );\n}\n\nadd_shortcode( 'loginform', 'wpse_242473_login_form' );\n</code></pre>\n"
},
{
"answer_id": 243172,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 0,
"selected": false,
"text": "<p>There is the function <a href=\"https://developer.wordpress.org/reference/functions/wp_login_form/\" rel=\"nofollow\"><code>wp_login_form( [ /* array of arguments */ ] )</code></a>, which displays a login form that you can put into every template. When you look at the internals, you will see that the forms action points to:</p>\n\n<pre><code>esc_url( site_url( 'wp-login.php', 'login_post' ) )\n</code></pre>\n\n<p>…(at least if you did not use the <code>$args['redirect']</code> argument). This means that <code>wp-login.php</code> handles the sign on. Now you have multiple options:</p>\n\n<ol>\n<li><p>You can use the arguments for the function or globally set the filter <code>login_form_defaults</code>, which allows you to alter the default values, like <code>redirect</code>, which per default points to the current site:</p>\n\n<pre><code>( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],\n</code></pre>\n\n<p>Then you can use a filter to redirect based on the role (or perform a log out if the logged in user role did not match the role that you want to allow logging in from this template):</p>\n\n<pre><code> apply_filters( 'login_redirect', $redirect_to, $requested_redirect_to, $user );\n</code></pre></li>\n<li><p>You scratch that idea as you can not determine the difference between an <em>admin</em> and a <em>guest</em> as you do not know the role of a user <em>before</em> they logged in.</p></li>\n</ol>\n"
},
{
"answer_id": 243198,
"author": "davemac",
"author_id": 131,
"author_profile": "https://wordpress.stackexchange.com/users/131",
"pm_score": 0,
"selected": false,
"text": "<p>For a custom register user form, you can use <a href=\"https://www.advancedcustomfields.com/resources/create-a-front-end-form/\" rel=\"nofollow\">Advanced Custom Fields to create a front-end form</a>. </p>\n\n<p>You can set up the custom fields for the registration using ACF, and set the location rules for the field group when User Form is equal to Register, and Add/Edit. </p>\n\n<p>I did something similar, hooking into the <code>acf/pre_save_post</code> filter and doing the following:</p>\n\n<ul>\n<li>sanitize the inputs</li>\n<li>register the user with <code>register_new_user()</code>, which handles the password generation and email notification </li>\n<li>use <code>wp_update_user()</code> and <code>update_user_meta()</code> to map the appropriate custom ACF fields to custom WP user profile fields</li>\n<li>set the new user's role</li>\n<li>use <code>wp_mail()</code> to email admin if required</li>\n</ul>\n\n<p>Some more information on <a href=\"https://support.advancedcustomfields.com/forums/topic/registering-new-user-with-acf/\" rel=\"nofollow\">registering a user with ACF</a> here.</p>\n\n<pre><code>function my_pre_save_user( $post_id ) { \n\n // If we have an email address, add the user\n // This field only exists in the new user field group\n if ( isset($_POST['acf']['add acf_field_ID here']) && !empty($_POST['acf']['add acf_field_ID here'])) {\n\n // sanitize our inputs\n $sanitized_email = sanitize_email( $_POST['acf']['add acf_field_ID here'] );\n $sanitized_firstname = sanitize_text_field( $_POST['acf']['add acf_field_ID here'] );\n $sanitized_lastname = sanitize_text_field( $_POST['acf']['add acf_field_ID here'] );\n $sanitized_contactnumber = sanitize_text_field( $_POST['acf']['add acf_field_ID here'] );\n\n // Prepare basic user info\n $username = $sanitized_email;\n $email = $sanitized_email;\n $display_name = $sanitized_firstname .' '. $sanitized_lastname;\n\n // Register the user and store the ID as $user_id, handles the validation, generates random password and send email notification to user\n $user_id = register_new_user( $username, $email );\n\n // If we get an error (eg user already exists)\n if( is_wp_error( $user_id ) ) {\n // Show the error\n echo 'Error: '.$user_id->get_error_message();\n // Exit\n exit;\n\n // Good to go\n } else {\n\n // get single value from post object\n $dmc_get_company_field = $_POST['acf']['add acf_field_ID here'];\n $dmc_selected_exhibitor = get_field( $dmc_get_company_field );\n\n // Update the new user's info\n wp_update_user( array(\n 'ID' => $user_id,\n 'first_name' => $sanitized_firstname,\n 'last_name' => $sanitized_lastname,\n 'display_name' => $display_name\n ));\n\n // update the new users's meta\n update_user_meta( $user_id, 'dmc_exhibitor_company_name', $dmc_get_company_field );\n update_user_meta( $user_id, 'dmc_exhibitor_contact_number', $sanitized_contactnumber );\n\n // update user role\n $user_id_role = new WP_User( $user_id );\n $user_id_role->set_role( 'contributor' );\n $profile_link = get_edit_user_link( $user_id );\n\n $to = \"[add email addresses here]\";\n $headers[] = 'MIME-Version: 1.0';\n $headers[] = 'Content-Type: text/html; charset=UTF-8';\n $headers[] = 'Reply-To: '. $username. ' <'. $email .'>';\n\n $subject = \"[add email subject here]\";\n $body = \"[add email body here]\";\n\n // send the email\n wp_mail( $to, $subject, $body, $headers );\n\n // redirect to thankyou page\n $redirect_url = get_bloginfo('url') . '[add URL to redirect to here]';\n wp_redirect( $redirect_url );\n\n // exit this script\n exit;\n\n }\n\n } else {\n return $post_id;\n }\n\n}\nadd_filter('acf/pre_save_post' , 'my_pre_save_user' );\n</code></pre>\n"
}
] |
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><code>array(\n [0] => WP_Term Object\n (\n [term_id] =>\n [name] =>\n [slug] =>\n [term_group] =>\n [term_taxonomy_id] =>\n [taxonomy] =>\n [description] =>\n [parent] =>\n [count] =>\n [filter] =>\n )\n)\n</code></pre>\n\n<p>You can process this with <code>wp_list_pluck</code> to turn it into an associative array, so for example:</p>\n\n<pre><code> $cat_counts = wp_list_pluck( get_categories(), 'count', 'name' );\n</code></pre>\n\n<p>This will return an array like:</p>\n\n<pre><code>array(\n 'Geography' => 5,\n 'Maths' => 7,\n 'English' => 3,\n)\n</code></pre>\n\n<p>For other taxonomies use <code>get_terms()</code> instead. <code>get_categories()</code> is really not much more than a wrapper for <code>get_terms()</code>.</p>\n\n<p>To show these like the picture you've added to your question, just loop over the array.</p>\n\n<pre><code>echo '<dl>';\n// use whichever HTML structure you feel is appropriate\n\nforeach ( $cat_counts as $name => $count ) {\n echo '<dt>' . $name . '</dt>';\n echo '<dd>' . sprintf( \"%02d\", $count ) . '</dd>';\n // use sprintf to specify 2 decimal characters with leading zero if necessary\n}\n\necho '</dl>';\n</code></pre>\n"
},
{
"answer_id": 242651,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/get_category/\" rel=\"nofollow\"><code>get_category()</code></a>, it returns an object, with the for you relevant property <code>category_count</code>.</p>\n"
}
] |
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 dimensions:</p>\n\n<pre><code>add_filter('wp_handle_upload_prefilter','tc_handle_upload_prefilter');\nfunction tc_handle_upload_prefilter($file)\n{\n\n $img=getimagesize($file['tmp_name']);\n $minimum = array('width' => '250', 'height' => '200');\n $width= $img[0];\n $height =$img[1];\n\n if ($width < $minimum['width'] )\n return array(\"error\"=>\"Image dimensions are too small. Minimum width is {$minimum['width']}px. Uploaded image width is $width px\");\n\n elseif ($height < $minimum['height'])\n return array(\"error\"=>\"Image dimensions are too small. Minimum height is {$minimum['height']}px. Uploaded image height is $height px\");\n else\n return $file; \n}\n</code></pre>\n\n<p>Then just change the numbers of the minimum dimensions you want (in my example is 250 and 200)</p>\n"
},
{
"answer_id": 243175,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 0,
"selected": false,
"text": "<p>Determining if an attachment actually is a <em>featured image</em> is easy: </p>\n\n<pre><code>get_post_thumbnail_id( get_post() );\n</code></pre>\n\n<p>which is a convenience function around</p>\n\n<pre><code>get_post_meta( get_post()->ID, '_thumbnail_id', true );\n</code></pre>\n\n<p>It is a bit more complicated if you know nothing than the File name or Url.</p>\n\n<pre><code>add_filter( 'wp_handle_upload_prefilter', function( $file ) {\n\n $url = wp_get_attachment_image_src( \n get_post_thumbnail_id( get_post() ),\n 'post-thumbnail'\n );\n\n // Output possible errors \n if ( false !== strpos( $url, $file ) ) {\n $file['error'] = 'Sorry, but we only allow featured images';\n }\n\n return $file;\n} );\n</code></pre>\n\n<p>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 <code>wp_handle_upload_prefilter</code> might be too early.</p>\n\n<p>Another option might be to use the last filter inside <code>_wp_handle_upload()</code>:</p>\n\n<pre><code>apply_filters( 'wp_handle_upload', array(\n 'file' => $new_file,\n 'url' => $url,\n 'type' => $type\n), 'wp_handle_sideload' === $action ? 'sideload' : 'upload' );\n</code></pre>\n\n<p>which handles sideload as well.</p>\n\n<p>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.</p>\n\n<p>The meta box itself is registered with <code>add_meta_box()</code> and the box callback is <code>post_thumbnail_meta_box</code>, which calls <code>_wp_post_thumbnail_html()</code> to render the contents. When you look in there, you will see that there is actually a hidden field:</p>\n\n<pre><code>$content .= '<input type=\"hidden\" id=\"_thumbnail_id\" name=\"_thumbnail_id\" value=\"' . esc_attr( $thumbnail_id ? $thumbnail_id : '-1' ) . '\" />';\n</code></pre>\n\n<p>Now the <code>name</code> is <code>_thumbnail_id</code>, which you should be able to fetch with <code>filter_input()</code> (good) or with <code>$_POST['_thumbnail_id']</code> (bad) inside a callback like <code>wp_handle_upload_prefilter</code> to determine if it actually was a featured image:</p>\n\n<pre><code>$featID = filter_input( INPUT_POST, '_thumbnail_id', … filters … );\n</code></pre>\n"
}
] |
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:</p>\n\n<pre><code>function all_queried_items(){\n\n global $wp_query;\n\n $all_queried_posts = $wp_query->posts;\n\n}\n\nadd_action('wp', 'all_queried_items');\n</code></pre>\n"
},
{
"answer_id": 242703,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<h2>Extending the <code>wpdb</code> class</h2>\n\n<p>We can create the <code>db.php</code> file under <code>wp-content/</code> directory to override the <code>wpdb</code> class to our needs. </p>\n\n<p>I checked this site for such examples and found one by @MarkKaplun <a href=\"https://wordpress.stackexchange.com/a/160819/26350\">here</a>.</p>\n\n<p>Here's an example how one can get access to the <em>last result</em>, after each query has run:</p>\n\n<pre><code><?php\n/**\n * db.php - Override the global $wpdb object to collect all query results\n */\nnamespace WPSE\\Question242685;\n\nclass DB extends \\wpdb\n{\n public function __construct( $dbuser, $dbpassword, $dbname, $dbhost )\n {\n // Parent constructor\n parent::__construct( $dbuser, $dbpassword, $dbname, $dbhost );\n }\n\n public function query( $query )\n {\n // Parent query\n $val = parent::query( $query );\n\n //----------------------------------------------------------------------\n // Edit this to your needs\n //\n // Warning: It can be slow and resource demanding to collect all results \n if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )\n {\n // do something with $this->last_result;\n }\n //----------------------------------------------------------------------\n\n return $val;\n }\n\n} // end class\n\n// Override the global wpdb object\n$GLOBALS['wpdb'] = new DB( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );\n</code></pre>\n\n<p>Here we assume the <code>SAVEQUERIES</code> is defined as <code>true</code> in the <code>wp-config.php</code> file.</p>\n\n<p><strong>Note</strong> that collecting <em>all</em> the results can be <em>resource demanding</em>, so you better only test this on a dev install.</p>\n"
}
] |
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_uri()</code> for parent theme</p>\n\n<p>and</p>\n\n<p><code>get_stylesheet_directory_uri()</code> for child theme or parent theme if not child theme present</p>\n\n<p>NOTE: this will require a slash like so:</p>\n\n<pre><code> $image_link_url = get_template_directory_uri() . '/images/placeholder_bg.png';\n</code></pre>\n"
},
{
"answer_id": 242690,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 0,
"selected": false,
"text": "<p>As far I've understood you want show a default image which you've store in a folder in your theme directory. So for that I think your code should be modeified a little bit-</p>\n\n<pre><code>if ( has_featured_image() ) {\n $image_link_url = $featured_background_image;\n} else {\n $image_link_url = get_stylesheet_directory_uri() . '/images/placeholder_bg.png';\n}\n</code></pre>\n\n<p>Please try the above code. I hope that will work.</p>\n"
},
{
"answer_id": 242692,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>has_post_thumbnail()</code> instead of <code>has_featured_image()</code> and <code>get_template_directory_uri()</code> instead of <code>get_template_url()</code>.</p>\n\n<pre><code>if(has_post_thumbnail()){\n $image_link_url = wp_get_attachment_image_url( $post_thumbnail_id, $size );\n}else {\n$image_link_url = get_template_directory_uri() . 'images/placeholder_bg.png';\n}\n</code></pre>\n"
}
] |
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', 'second_type_product', 'third_type_product'</code> . Ensure that you have correct words there.</p>\n"
},
{
"answer_id": 243394,
"author": "Pascal Knecht",
"author_id": 105101,
"author_profile": "https://wordpress.stackexchange.com/users/105101",
"pm_score": 0,
"selected": false,
"text": "<p>I would debug it like following:</p>\n\n<ul>\n<li>Check where the error is being thrown - This almost for certain in the wp-admin/edit.php file - debug the $post_type variable there</li>\n<li>Try to set the post type variable in your pre_get_posts query correctly</li>\n</ul>\n\n<p>Furthermore, it would be nice if you could share some code with which I can test your problem.</p>\n"
},
{
"answer_id": 243397,
"author": "Nabil Kadimi",
"author_id": 17187,
"author_profile": "https://wordpress.stackexchange.com/users/17187",
"pm_score": 0,
"selected": false,
"text": "<p>Your code is fine. From the error message and the URL parameters, I can guess there is not CPT <code>product</code> in your install, it would work if you replace use any post types registered (<code>post</code>, <code>page</code>, ...) or added a CPT <code>product</code> (by installing WooCommerce for example).</p>\n\n<p>And by the way, I believe you are replacing all posts listing pages on the dashboard with the same page that lists <code>product</code>, <code>second_type_product</code> and <code>third_type_product</code>. Are you sure this is what you want?</p>\n"
}
] |
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('category') );\n$term_slugs = wp_list_pluck( $terms, 'slug' ); \n$args = array(\n 'post_per_page' => '-1',\n 'post_type' => array( 'products' ), \n 'tax_query' => array(\n array(\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => $term_slugs\n ) \n );\n\n\n $my_query = null;\n $my_query = new WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 242722,
"author": "Anish",
"author_id": 104559,
"author_profile": "https://wordpress.stackexchange.com/users/104559",
"pm_score": 4,
"selected": true,
"text": "<p>You are doing a little mistake in your <code>$pargs</code></p>\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">As per documentation</a></p>\n<blockquote>\n<p><strong>Important Note:</strong> 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"</p>\n</blockquote>\n<pre><code>$pargs = array(\n 'posts_per_page' => '-1',\n 'post_type' => 'products',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => 'specials'\n )\n )\n)\n</code></pre>\n"
}
] |
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 Plugin Directory Slurper</a> 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.:</p>\n\n<pre><code>grep -r --include=*.php 'wpseo_' ./\n</code></pre>\n\n<p>Unzip the WordPres Plugin Directory Slurper package to to your document root. The default directory name is <code>WordPress-Plugin-Directory-Slurper</code> and it contains:</p>\n\n<pre><code> /plugins/\n /readmes/\n /zips/\n LICENSE\n README.markdown\n update\n</code></pre>\n\n<p>Run the bash script by executing <code>php update</code> from within the <code>WordPress-Plugin-Directory-Slurper</code> directory. Zipped plugins will be downloaded to <code>/zips</code> and extracted to <code>/plugins</code>. The entire repo is somewhere around 15GB and will take several hours to download the first time.</p>\n\n<p>The contents of the <code>update</code> script:</p>\n\n<pre><code>#!/usr/bin/php\n<?php\n$args = $argv;\n$cmd = array_shift( $args );\n\n$type = 'all';\nif ( !empty( $args[0] ) ) {\n $type = $args[0];\n}\n\nswitch ( $type ) {\n case 'readme':\n $directory = 'readmes';\n $download = 'readmes/%s.readme';\n $url = 'http://plugins.svn.wordpress.org/%s/trunk/readme.txt';\n break;\n case 'all':\n $directory = 'plugins';\n $download = 'zips/%s.zip';\n $url = 'http://downloads.wordpress.org/plugin/%s.latest-stable.zip?nostats=1';\n break;\n default:\n echo $cmd . \": invalid command\\r\\n\";\n echo 'Usage: php ' . $cmd . \" [command]\\r\\n\\r\\n\";\n echo \"Available commands:\\r\\n\";\n echo \" all - Downloads full plugin zips\\r\\n\";\n echo \" readme - Downloads plugin readmes only\\r\\n\";\n die();\n}\n\necho \"Determining most recent SVN revision...\\r\\n\";\ntry {\n $changelog = @file_get_contents( 'http://plugins.trac.wordpress.org/log/?format=changelog&stop_rev=HEAD' );\n if ( !$changelog )\n throw new Exception( 'Could not fetch the SVN changelog' );\n preg_match( '#\\[([0-9]+)\\]#', $changelog, $matches );\n if ( !$matches[1] )\n throw new Exception( 'Could not determine most recent revision.' );\n} catch ( Exception $e ) {\n die( $e->getMessage() . \"\\r\\n\" );\n}\n$svn_last_revision = (int) $matches[1];\necho \"Most recent SVN revision: \" . $svn_last_revision . \"\\r\\n\";\nif ( file_exists( $directory . '/.last-revision' ) ) {\n $last_revision = (int) file_get_contents( $directory . '/.last-revision' );\n echo \"Last synced revision: \" . $last_revision . \"\\r\\n\";\n} else {\n $last_revision = false;\n echo \"You have not yet performed a successful sync. Settle in. This will take a while.\\r\\n\";\n}\n\n$start_time = time();\n\nif ( $last_revision != $svn_last_revision ) {\n if ( $last_revision ) {\n $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 );\n $changes = file_get_contents( $changelog_url );\n preg_match_all( '#^' . \"\\t\" . '*\\* ([^/A-Z ]+)[ /].* \\((added|modified|deleted|moved|copied)\\)' . \"\\n\" . '#m', $changes, $matches );\n $plugins = array_unique( $matches[1] );\n } else {\n $plugins = file_get_contents( 'http://svn.wp-plugins.org/' );\n preg_match_all( '#<li><a href=\"([^/]+)/\">([^/]+)/</a></li>#', $plugins, $matches );\n $plugins = $matches[1];\n }\n\n foreach ( $plugins as $plugin ) {\n $plugin = urldecode( $plugin );\n echo \"Updating \" . $plugin;\n\n $output = null; $return = null;\n exec( 'wget -q -np -O ' . escapeshellarg( sprintf($download, $plugin) ) . ' ' . escapeshellarg( sprintf($url, $plugin) ) . ' > /dev/null', $output, $return );\n\n if ( $return === 0 && file_exists( sprintf($download, $plugin) ) ) {\n if ($type === 'all') {\n if ( file_exists( 'plugins/' . $plugin ) )\n exec( 'rm -rf ' . escapeshellarg( 'plugins/' . $plugin ) );\n\n exec( 'unzip -o -d plugins ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );\n exec( 'rm -rf ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );\n }\n } else {\n echo '... download failed.';\n }\n echo \"\\r\\n\";\n }\n\n if ( file_put_contents( $directory . '/.last-revision', $svn_last_revision ) )\n echo \"[CLEANUP] Updated $directory/.last-revision to \" . $svn_last_revision . \"\\r\\n\";\n else\n echo \"[ERROR] Could not update $directory/.last-revision to \" . $svn_last_revision . \"\\r\\n\";\n}\n\n$end_time = time();\n$minutes = ( $end_time - $start_time ) / 60;\n$seconds = ( $end_time - $start_time ) % 60;\n\necho \"[SUCCESS] Done updating plugins!\\r\\n\";\necho \"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\";\necho \"[DONE]\\r\\n\";\n</code></pre>\n\n<p>If you'd like to download all of the most recent approved themes, there's a script for that too: <a href=\"https://github.com/aaronjorbin/WordPress-Theme-Directory-Slurper\">WordPress Theme Directory Slurper</a> by Aaron Jorbin.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 243061,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>don't be generic, use some variation of your name.</li>\n<li>No one that installs new plugins uses PHP 5.2 anymore (oct 2016), just use PHP namespace, and make it something long but relevant like the plugin name.</li>\n</ol>\n"
}
] |
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 Plugin Directory Slurper</a> 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.:</p>\n\n<pre><code>grep -r --include=*.php 'wpseo_' ./\n</code></pre>\n\n<p>Unzip the WordPres Plugin Directory Slurper package to to your document root. The default directory name is <code>WordPress-Plugin-Directory-Slurper</code> and it contains:</p>\n\n<pre><code> /plugins/\n /readmes/\n /zips/\n LICENSE\n README.markdown\n update\n</code></pre>\n\n<p>Run the bash script by executing <code>php update</code> from within the <code>WordPress-Plugin-Directory-Slurper</code> directory. Zipped plugins will be downloaded to <code>/zips</code> and extracted to <code>/plugins</code>. The entire repo is somewhere around 15GB and will take several hours to download the first time.</p>\n\n<p>The contents of the <code>update</code> script:</p>\n\n<pre><code>#!/usr/bin/php\n<?php\n$args = $argv;\n$cmd = array_shift( $args );\n\n$type = 'all';\nif ( !empty( $args[0] ) ) {\n $type = $args[0];\n}\n\nswitch ( $type ) {\n case 'readme':\n $directory = 'readmes';\n $download = 'readmes/%s.readme';\n $url = 'http://plugins.svn.wordpress.org/%s/trunk/readme.txt';\n break;\n case 'all':\n $directory = 'plugins';\n $download = 'zips/%s.zip';\n $url = 'http://downloads.wordpress.org/plugin/%s.latest-stable.zip?nostats=1';\n break;\n default:\n echo $cmd . \": invalid command\\r\\n\";\n echo 'Usage: php ' . $cmd . \" [command]\\r\\n\\r\\n\";\n echo \"Available commands:\\r\\n\";\n echo \" all - Downloads full plugin zips\\r\\n\";\n echo \" readme - Downloads plugin readmes only\\r\\n\";\n die();\n}\n\necho \"Determining most recent SVN revision...\\r\\n\";\ntry {\n $changelog = @file_get_contents( 'http://plugins.trac.wordpress.org/log/?format=changelog&stop_rev=HEAD' );\n if ( !$changelog )\n throw new Exception( 'Could not fetch the SVN changelog' );\n preg_match( '#\\[([0-9]+)\\]#', $changelog, $matches );\n if ( !$matches[1] )\n throw new Exception( 'Could not determine most recent revision.' );\n} catch ( Exception $e ) {\n die( $e->getMessage() . \"\\r\\n\" );\n}\n$svn_last_revision = (int) $matches[1];\necho \"Most recent SVN revision: \" . $svn_last_revision . \"\\r\\n\";\nif ( file_exists( $directory . '/.last-revision' ) ) {\n $last_revision = (int) file_get_contents( $directory . '/.last-revision' );\n echo \"Last synced revision: \" . $last_revision . \"\\r\\n\";\n} else {\n $last_revision = false;\n echo \"You have not yet performed a successful sync. Settle in. This will take a while.\\r\\n\";\n}\n\n$start_time = time();\n\nif ( $last_revision != $svn_last_revision ) {\n if ( $last_revision ) {\n $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 );\n $changes = file_get_contents( $changelog_url );\n preg_match_all( '#^' . \"\\t\" . '*\\* ([^/A-Z ]+)[ /].* \\((added|modified|deleted|moved|copied)\\)' . \"\\n\" . '#m', $changes, $matches );\n $plugins = array_unique( $matches[1] );\n } else {\n $plugins = file_get_contents( 'http://svn.wp-plugins.org/' );\n preg_match_all( '#<li><a href=\"([^/]+)/\">([^/]+)/</a></li>#', $plugins, $matches );\n $plugins = $matches[1];\n }\n\n foreach ( $plugins as $plugin ) {\n $plugin = urldecode( $plugin );\n echo \"Updating \" . $plugin;\n\n $output = null; $return = null;\n exec( 'wget -q -np -O ' . escapeshellarg( sprintf($download, $plugin) ) . ' ' . escapeshellarg( sprintf($url, $plugin) ) . ' > /dev/null', $output, $return );\n\n if ( $return === 0 && file_exists( sprintf($download, $plugin) ) ) {\n if ($type === 'all') {\n if ( file_exists( 'plugins/' . $plugin ) )\n exec( 'rm -rf ' . escapeshellarg( 'plugins/' . $plugin ) );\n\n exec( 'unzip -o -d plugins ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );\n exec( 'rm -rf ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );\n }\n } else {\n echo '... download failed.';\n }\n echo \"\\r\\n\";\n }\n\n if ( file_put_contents( $directory . '/.last-revision', $svn_last_revision ) )\n echo \"[CLEANUP] Updated $directory/.last-revision to \" . $svn_last_revision . \"\\r\\n\";\n else\n echo \"[ERROR] Could not update $directory/.last-revision to \" . $svn_last_revision . \"\\r\\n\";\n}\n\n$end_time = time();\n$minutes = ( $end_time - $start_time ) / 60;\n$seconds = ( $end_time - $start_time ) % 60;\n\necho \"[SUCCESS] Done updating plugins!\\r\\n\";\necho \"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\";\necho \"[DONE]\\r\\n\";\n</code></pre>\n\n<p>If you'd like to download all of the most recent approved themes, there's a script for that too: <a href=\"https://github.com/aaronjorbin/WordPress-Theme-Directory-Slurper\">WordPress Theme Directory Slurper</a> by Aaron Jorbin.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 243061,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>don't be generic, use some variation of your name.</li>\n<li>No one that installs new plugins uses PHP 5.2 anymore (oct 2016), just use PHP namespace, and make it something long but relevant like the plugin name.</li>\n</ol>\n"
}
] |
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 Plugin Directory Slurper</a> 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.:</p>\n\n<pre><code>grep -r --include=*.php 'wpseo_' ./\n</code></pre>\n\n<p>Unzip the WordPres Plugin Directory Slurper package to to your document root. The default directory name is <code>WordPress-Plugin-Directory-Slurper</code> and it contains:</p>\n\n<pre><code> /plugins/\n /readmes/\n /zips/\n LICENSE\n README.markdown\n update\n</code></pre>\n\n<p>Run the bash script by executing <code>php update</code> from within the <code>WordPress-Plugin-Directory-Slurper</code> directory. Zipped plugins will be downloaded to <code>/zips</code> and extracted to <code>/plugins</code>. The entire repo is somewhere around 15GB and will take several hours to download the first time.</p>\n\n<p>The contents of the <code>update</code> script:</p>\n\n<pre><code>#!/usr/bin/php\n<?php\n$args = $argv;\n$cmd = array_shift( $args );\n\n$type = 'all';\nif ( !empty( $args[0] ) ) {\n $type = $args[0];\n}\n\nswitch ( $type ) {\n case 'readme':\n $directory = 'readmes';\n $download = 'readmes/%s.readme';\n $url = 'http://plugins.svn.wordpress.org/%s/trunk/readme.txt';\n break;\n case 'all':\n $directory = 'plugins';\n $download = 'zips/%s.zip';\n $url = 'http://downloads.wordpress.org/plugin/%s.latest-stable.zip?nostats=1';\n break;\n default:\n echo $cmd . \": invalid command\\r\\n\";\n echo 'Usage: php ' . $cmd . \" [command]\\r\\n\\r\\n\";\n echo \"Available commands:\\r\\n\";\n echo \" all - Downloads full plugin zips\\r\\n\";\n echo \" readme - Downloads plugin readmes only\\r\\n\";\n die();\n}\n\necho \"Determining most recent SVN revision...\\r\\n\";\ntry {\n $changelog = @file_get_contents( 'http://plugins.trac.wordpress.org/log/?format=changelog&stop_rev=HEAD' );\n if ( !$changelog )\n throw new Exception( 'Could not fetch the SVN changelog' );\n preg_match( '#\\[([0-9]+)\\]#', $changelog, $matches );\n if ( !$matches[1] )\n throw new Exception( 'Could not determine most recent revision.' );\n} catch ( Exception $e ) {\n die( $e->getMessage() . \"\\r\\n\" );\n}\n$svn_last_revision = (int) $matches[1];\necho \"Most recent SVN revision: \" . $svn_last_revision . \"\\r\\n\";\nif ( file_exists( $directory . '/.last-revision' ) ) {\n $last_revision = (int) file_get_contents( $directory . '/.last-revision' );\n echo \"Last synced revision: \" . $last_revision . \"\\r\\n\";\n} else {\n $last_revision = false;\n echo \"You have not yet performed a successful sync. Settle in. This will take a while.\\r\\n\";\n}\n\n$start_time = time();\n\nif ( $last_revision != $svn_last_revision ) {\n if ( $last_revision ) {\n $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 );\n $changes = file_get_contents( $changelog_url );\n preg_match_all( '#^' . \"\\t\" . '*\\* ([^/A-Z ]+)[ /].* \\((added|modified|deleted|moved|copied)\\)' . \"\\n\" . '#m', $changes, $matches );\n $plugins = array_unique( $matches[1] );\n } else {\n $plugins = file_get_contents( 'http://svn.wp-plugins.org/' );\n preg_match_all( '#<li><a href=\"([^/]+)/\">([^/]+)/</a></li>#', $plugins, $matches );\n $plugins = $matches[1];\n }\n\n foreach ( $plugins as $plugin ) {\n $plugin = urldecode( $plugin );\n echo \"Updating \" . $plugin;\n\n $output = null; $return = null;\n exec( 'wget -q -np -O ' . escapeshellarg( sprintf($download, $plugin) ) . ' ' . escapeshellarg( sprintf($url, $plugin) ) . ' > /dev/null', $output, $return );\n\n if ( $return === 0 && file_exists( sprintf($download, $plugin) ) ) {\n if ($type === 'all') {\n if ( file_exists( 'plugins/' . $plugin ) )\n exec( 'rm -rf ' . escapeshellarg( 'plugins/' . $plugin ) );\n\n exec( 'unzip -o -d plugins ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );\n exec( 'rm -rf ' . escapeshellarg( 'zips/' . $plugin . '.zip' ) );\n }\n } else {\n echo '... download failed.';\n }\n echo \"\\r\\n\";\n }\n\n if ( file_put_contents( $directory . '/.last-revision', $svn_last_revision ) )\n echo \"[CLEANUP] Updated $directory/.last-revision to \" . $svn_last_revision . \"\\r\\n\";\n else\n echo \"[ERROR] Could not update $directory/.last-revision to \" . $svn_last_revision . \"\\r\\n\";\n}\n\n$end_time = time();\n$minutes = ( $end_time - $start_time ) / 60;\n$seconds = ( $end_time - $start_time ) % 60;\n\necho \"[SUCCESS] Done updating plugins!\\r\\n\";\necho \"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\";\necho \"[DONE]\\r\\n\";\n</code></pre>\n\n<p>If you'd like to download all of the most recent approved themes, there's a script for that too: <a href=\"https://github.com/aaronjorbin/WordPress-Theme-Directory-Slurper\">WordPress Theme Directory Slurper</a> by Aaron Jorbin.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 243061,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>don't be generic, use some variation of your name.</li>\n<li>No one that installs new plugins uses PHP 5.2 anymore (oct 2016), just use PHP namespace, and make it something long but relevant like the plugin name.</li>\n</ol>\n"
}
] |
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 PHP documentation says</a></p>\n<p>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.</p>\n</blockquote>\n<p>So You have to use <code>curly braces</code> <code>{}</code> to add more statement within <code>if</code> <code>else</code></p>\n<pre><code><?php if ( $paged < 2 ) {\necho 'some text';\n?>\n<p>\n Text...\n <?php $published_posts = wp_count_posts('item');\n echo $published_posts->publish; ?>\n text...\n <?php echo do_shortcode("[count]"); ?>\n text.\n</p>\n<?php\n} else {\n echo 'some other text'; \n} ?>\n</code></pre>\n"
},
{
"answer_id": 242798,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php if ( $paged < 2 ) :\n\n echo 'some text';\n\n $published_posts = wp_count_posts( 'item' );\n\n printf( \"<p>%s%s%s%s%s</p>\",\n\n 'Text...',\n\n isset( $published_posts->publish ) ? $published_posts->publish : '',\n\n 'text...',\n\n do_shortcode( \"[count]\" ),\n\n 'text...' );\n\nelse :\n\n ?>some other text<?php\n\nendif; ?>\n</code></pre>\n\n<p>You can use any combination of functions that gets the job done and helps you see what you're doing effectively.</p>\n\n<pre><code><?php if ( 2 > $paged ) :\n\n ?>some text<?php\n\n $published_posts = wp_count_posts( 'item' );\n\n printf ( \"<p>%s%s%s%s%s</p>\",\n\n 'Text...',\n\n isset( $published_posts->publish ) ? $published_posts->publish : '',\n\n 'text...',\n\n do_shortcode( \"[count]\" ),\n\n 'text...' );\n\nelse :\n\n echo implode( PHP_EOL, array (\n 'some',\n 'other',\n 'text',\n ) );\n\nendif; ?>\n</code></pre>\n\n<blockquote>\n <ul>\n <li><a href=\"http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary\" rel=\"nofollow\">Ternary Operator</a></li>\n <li><a href=\"http://www.w3schools.com/php/php_if_else.asp\" rel=\"nofollow\"><code>if... else..</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.printf.php\" rel=\"nofollow\"><code>printf</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.sprintf.php\" rel=\"nofollow\"><code>sprintf</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.isset.php\" rel=\"nofollow\"><code>isset</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.implode.php\" rel=\"nofollow\"><code>implode</code></a></li>\n <li><a href=\"http://php.net/manual/en/reserved.constants.php#constant.php-eol\" rel=\"nofollow\"><code>PHP_EOL</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.echo.php\" rel=\"nofollow\"><code>echo</code></a></li>\n </ul>\n</blockquote>\n\n<p>If your nesting get really out of hand, it might make more sense to create partials that can be <a href=\"http://www.deluxeblogtips.com/2010/06/wordpress-include-template-files.html\" rel=\"nofollow\">included</a>.</p>\n\n<pre><code>include TEMPLATEPATH . '/template-name.php';\n\nload_template( TEMPLATEPATH . '/template-name.php' );\n\nlocate_template( $template_names, $load );\n\ninclude( get_query_template( 'template-name' ) );\n\nget_template_part( $slug, $name );\n</code></pre>\n\n<blockquote>\n <ul>\n <li><a href=\"http://php.net/manual/en/function.require.php\" rel=\"nofollow\"><code>require</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.include.php\" rel=\"nofollow\"><code>include</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.include-once.php\" rel=\"nofollow\"><code>include_once</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.require-once.php\" rel=\"nofollow\"><code>require_once</code></a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/load_template/\" rel=\"nofollow\"><code>load_template</code></a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow\"><code>locate_template</code></a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/get_query_template/\" rel=\"nofollow\"><code>get_query_template</code></a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow\"><code>get_template_part</code></a></li>\n </ul>\n</blockquote>\n\n<p>WordPress does have some <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/\" rel=\"nofollow\">coding standards</a> you can follow or utilize with other tools like CodeSniffer as <a href=\"https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards\" rel=\"nofollow\">Standards</a>.</p>\n\n<pre><code># check\n\nphpcs --standard=WordPress\n\n# fix\n\nphpcbf --standard=WordPress\n</code></pre>\n"
}
] |
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 [email protected] 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 PHP documentation says</a></p>\n<p>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.</p>\n</blockquote>\n<p>So You have to use <code>curly braces</code> <code>{}</code> to add more statement within <code>if</code> <code>else</code></p>\n<pre><code><?php if ( $paged < 2 ) {\necho 'some text';\n?>\n<p>\n Text...\n <?php $published_posts = wp_count_posts('item');\n echo $published_posts->publish; ?>\n text...\n <?php echo do_shortcode("[count]"); ?>\n text.\n</p>\n<?php\n} else {\n echo 'some other text'; \n} ?>\n</code></pre>\n"
},
{
"answer_id": 242798,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php if ( $paged < 2 ) :\n\n echo 'some text';\n\n $published_posts = wp_count_posts( 'item' );\n\n printf( \"<p>%s%s%s%s%s</p>\",\n\n 'Text...',\n\n isset( $published_posts->publish ) ? $published_posts->publish : '',\n\n 'text...',\n\n do_shortcode( \"[count]\" ),\n\n 'text...' );\n\nelse :\n\n ?>some other text<?php\n\nendif; ?>\n</code></pre>\n\n<p>You can use any combination of functions that gets the job done and helps you see what you're doing effectively.</p>\n\n<pre><code><?php if ( 2 > $paged ) :\n\n ?>some text<?php\n\n $published_posts = wp_count_posts( 'item' );\n\n printf ( \"<p>%s%s%s%s%s</p>\",\n\n 'Text...',\n\n isset( $published_posts->publish ) ? $published_posts->publish : '',\n\n 'text...',\n\n do_shortcode( \"[count]\" ),\n\n 'text...' );\n\nelse :\n\n echo implode( PHP_EOL, array (\n 'some',\n 'other',\n 'text',\n ) );\n\nendif; ?>\n</code></pre>\n\n<blockquote>\n <ul>\n <li><a href=\"http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary\" rel=\"nofollow\">Ternary Operator</a></li>\n <li><a href=\"http://www.w3schools.com/php/php_if_else.asp\" rel=\"nofollow\"><code>if... else..</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.printf.php\" rel=\"nofollow\"><code>printf</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.sprintf.php\" rel=\"nofollow\"><code>sprintf</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.isset.php\" rel=\"nofollow\"><code>isset</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.implode.php\" rel=\"nofollow\"><code>implode</code></a></li>\n <li><a href=\"http://php.net/manual/en/reserved.constants.php#constant.php-eol\" rel=\"nofollow\"><code>PHP_EOL</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.echo.php\" rel=\"nofollow\"><code>echo</code></a></li>\n </ul>\n</blockquote>\n\n<p>If your nesting get really out of hand, it might make more sense to create partials that can be <a href=\"http://www.deluxeblogtips.com/2010/06/wordpress-include-template-files.html\" rel=\"nofollow\">included</a>.</p>\n\n<pre><code>include TEMPLATEPATH . '/template-name.php';\n\nload_template( TEMPLATEPATH . '/template-name.php' );\n\nlocate_template( $template_names, $load );\n\ninclude( get_query_template( 'template-name' ) );\n\nget_template_part( $slug, $name );\n</code></pre>\n\n<blockquote>\n <ul>\n <li><a href=\"http://php.net/manual/en/function.require.php\" rel=\"nofollow\"><code>require</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.include.php\" rel=\"nofollow\"><code>include</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.include-once.php\" rel=\"nofollow\"><code>include_once</code></a></li>\n <li><a href=\"http://php.net/manual/en/function.require-once.php\" rel=\"nofollow\"><code>require_once</code></a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/load_template/\" rel=\"nofollow\"><code>load_template</code></a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow\"><code>locate_template</code></a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/get_query_template/\" rel=\"nofollow\"><code>get_query_template</code></a></li>\n <li><a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow\"><code>get_template_part</code></a></li>\n </ul>\n</blockquote>\n\n<p>WordPress does have some <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/\" rel=\"nofollow\">coding standards</a> you can follow or utilize with other tools like CodeSniffer as <a href=\"https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards\" rel=\"nofollow\">Standards</a>.</p>\n\n<pre><code># check\n\nphpcs --standard=WordPress\n\n# fix\n\nphpcbf --standard=WordPress\n</code></pre>\n"
}
] |
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 [email protected] 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=\"nofollow\">https://wordpress.org/plugins/advanced-access-manager/</a> ) Plugin to restrict users in backend according to their roles....</p>\n\n<p>I thing this will be a better solution for your issue.</p>\n"
},
{
"answer_id": 244004,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<pre><code>if( is_admin() ) {\n add_filter( 'init', 'custom_restrict_pages_from_admin' );\n}\n\nfunction custom_restrict_pages_from_admin() {\n global $pagenow;\n\n $arr = array(\n 'update-core.php',\n 'edit.php'\n );\n\n if( custom_check_user_roles() && in_array( $pagenow , $arr ) ) {\n //echo some custom messages or call the functions \n } else {\n echo 'This page has restricted access to specific roles';\n wp_die();\n }\n}\n\nfunction custom_check_user_roles() {\n //restrict pages by user role \n\n if( current_user_can( 'administrator' ) || current_user_can( 'editor' ) ) \n return true;\n else { \n echo 'Not allowed!'; \n wp_die();\n }\n}\n</code></pre>\n"
}
] |
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=\"nofollow\">https://wordpress.org/plugins/advanced-access-manager/</a> ) Plugin to restrict users in backend according to their roles....</p>\n\n<p>I thing this will be a better solution for your issue.</p>\n"
},
{
"answer_id": 244004,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<pre><code>if( is_admin() ) {\n add_filter( 'init', 'custom_restrict_pages_from_admin' );\n}\n\nfunction custom_restrict_pages_from_admin() {\n global $pagenow;\n\n $arr = array(\n 'update-core.php',\n 'edit.php'\n );\n\n if( custom_check_user_roles() && in_array( $pagenow , $arr ) ) {\n //echo some custom messages or call the functions \n } else {\n echo 'This page has restricted access to specific roles';\n wp_die();\n }\n}\n\nfunction custom_check_user_roles() {\n //restrict pages by user role \n\n if( current_user_can( 'administrator' ) || current_user_can( 'editor' ) ) \n return true;\n else { \n echo 'Not allowed!'; \n wp_die();\n }\n}\n</code></pre>\n"
}
] |
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=\"nofollow\">https://wordpress.org/plugins/advanced-access-manager/</a> ) Plugin to restrict users in backend according to their roles....</p>\n\n<p>I thing this will be a better solution for your issue.</p>\n"
},
{
"answer_id": 244004,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<pre><code>if( is_admin() ) {\n add_filter( 'init', 'custom_restrict_pages_from_admin' );\n}\n\nfunction custom_restrict_pages_from_admin() {\n global $pagenow;\n\n $arr = array(\n 'update-core.php',\n 'edit.php'\n );\n\n if( custom_check_user_roles() && in_array( $pagenow , $arr ) ) {\n //echo some custom messages or call the functions \n } else {\n echo 'This page has restricted access to specific roles';\n wp_die();\n }\n}\n\nfunction custom_check_user_roles() {\n //restrict pages by user role \n\n if( current_user_can( 'administrator' ) || current_user_can( 'editor' ) ) \n return true;\n else { \n echo 'Not allowed!'; \n wp_die();\n }\n}\n</code></pre>\n"
}
] |
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=\"nofollow\">https://wordpress.org/plugins/advanced-access-manager/</a> ) Plugin to restrict users in backend according to their roles....</p>\n\n<p>I thing this will be a better solution for your issue.</p>\n"
},
{
"answer_id": 244004,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<pre><code>if( is_admin() ) {\n add_filter( 'init', 'custom_restrict_pages_from_admin' );\n}\n\nfunction custom_restrict_pages_from_admin() {\n global $pagenow;\n\n $arr = array(\n 'update-core.php',\n 'edit.php'\n );\n\n if( custom_check_user_roles() && in_array( $pagenow , $arr ) ) {\n //echo some custom messages or call the functions \n } else {\n echo 'This page has restricted access to specific roles';\n wp_die();\n }\n}\n\nfunction custom_check_user_roles() {\n //restrict pages by user role \n\n if( current_user_can( 'administrator' ) || current_user_can( 'editor' ) ) \n return true;\n else { \n echo 'Not allowed!'; \n wp_die();\n }\n}\n</code></pre>\n"
}
] |
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=\"nofollow\">https://wordpress.org/plugins/advanced-access-manager/</a> ) Plugin to restrict users in backend according to their roles....</p>\n\n<p>I thing this will be a better solution for your issue.</p>\n"
},
{
"answer_id": 244004,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<pre><code>if( is_admin() ) {\n add_filter( 'init', 'custom_restrict_pages_from_admin' );\n}\n\nfunction custom_restrict_pages_from_admin() {\n global $pagenow;\n\n $arr = array(\n 'update-core.php',\n 'edit.php'\n );\n\n if( custom_check_user_roles() && in_array( $pagenow , $arr ) ) {\n //echo some custom messages or call the functions \n } else {\n echo 'This page has restricted access to specific roles';\n wp_die();\n }\n}\n\nfunction custom_check_user_roles() {\n //restrict pages by user role \n\n if( current_user_can( 'administrator' ) || current_user_can( 'editor' ) ) \n return true;\n else { \n echo 'Not allowed!'; \n wp_die();\n }\n}\n</code></pre>\n"
}
] |
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\n<pre><code><?php\nadd_action( 'pre_get_posts', 'my_change_sort_order'); \nfunction my_change_sort_order( $query ){\n\n if ( ! is_admin() && $query->is_main_query() ) :\n\n if ( is_front_page() ) :\n //Set the order ASC or DESC\n $query->set( 'order', 'ASC' );\n //Set the orderby\n $query->set( 'orderby', 'title' );\n endif;\n\n endif;\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 242880,
"author": "vladiuk",
"author_id": 105039,
"author_profile": "https://wordpress.stackexchange.com/users/105039",
"pm_score": -1,
"selected": false,
"text": "<p>Its working for me. Thx for help!</p>\n\n<pre><code> add_action( 'pre_get_posts', 'my_change_sort_order'); \n function my_change_sort_order( $query ){\n\n if ( ! is_admin() && $query->is_main_query() ) :\n\n if ( is_archive() ) :\n //Set the order ASC or DESC\n $query->set( 'order', 'ASC' );\n //Set the orderby\n $query->set( 'orderby', 'title' );\n endif;\n\n endif;\n }\n</code></pre>\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>\n\n<pre><code> <!-- loop through the posts -->\n <?php while ( have_posts() ) : the_post(); ?>\n\n <article id=\"post-<?php the_ID(); ?>\" <?php post_class(); ?>>\n <div class=\"entry-content\">\n <?php the_content(); ?> <!-- post content -->\n\n </div><!-- .entry-content -->\n\n </article><!-- #post-## -->\n\n\n\n\n <?php endwhile; // end of the loop. ?>\n</code></pre>\n\n<p>What the above snippet will do is go through every post on your site and include a very simple name, post type, and the actual post itself all within an tag for each post.</p>\n\n<p>You probably should place this snippet within the with the ID \"main\", but you can put it anywhere you want -- on any page (not just the front)</p>\n\n<p>Enjoy</p>\n"
},
{
"answer_id": 242923,
"author": "VihangaAW",
"author_id": 105067,
"author_profile": "https://wordpress.stackexchange.com/users/105067",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it in two different ways</p>\n\n<p>01) Go to Settings > Reading and make the designation change and click “save changes”.\n<a href=\"https://i.stack.imgur.com/98af1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/98af1.png\" alt=\"enter image description here\"></a></p>\n\n<p>02) Go to Appearance > Customize > Static Front Page and choose to display the latest posts. </p>\n"
}
] |
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 <code>$wp_query</code> is set:</p>\n\n<pre><code>global $wp_query;\n\nif ( ! isset( $wp_query ) ) {\n _doing_it_wrong( __FUNCTION__, \n __( 'Conditional query tags do not work before the query is run.\n Before then, they always return false.' ), '3.1.0' );\n return false;\n}\n</code></pre>\n\n<p>Note that you're unsetting it with:</p>\n\n<pre><code>$wp_query = null;\n</code></pre>\n\n<p>just before you create a new <code>WP_Query</code> subquery, that calls <code>is_search()</code> when <code>pre_get_posts</code> fires. </p>\n\n<p>That's when the <code>_doing_it_wrong()</code> is activated.</p>\n\n<h2>Workaround</h2>\n\n<p>Always try to use the <em>main query</em>, instead of extra <code>WP_Query</code> sub-queries if possible, to avoid running extra database queries.</p>\n\n<p>To target the main search query in the front-end, we can use:</p>\n\n<pre><code>add_action('pre_get_posts', function( \\WP_Query $q ) {\n if ( \n ! is_admin() // Only target the front-end\n && $q->is_main_query() // Target the main query\n && $q->is_search() // Target a search query\n ) {\n // do stuff\n }\n});\n</code></pre>\n"
},
{
"answer_id": 290282,
"author": "Aness",
"author_id": 134345,
"author_profile": "https://wordpress.stackexchange.com/users/134345",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks @birgire. Got a similar issue here with the following error message and got it fixed up by commenting out the line : <code>$wp_query = null;</code></p>\n\n<p>Error message:</p>\n\n<blockquote>\n <p>Notice : is_home was called incorrectly . Conditional query tags do\n not work before the query is run. Before then, they always return\n false. Please see Debugging in WordPress for more information. (This\n message was added in version 3.1.0.) in (MYsyspath)/functions.php on\n line 4146</p>\n</blockquote>\n\n<p>And it worked, the culprit was the global variable unset action on my <code>index.php</code> </p>\n\n<pre><code>$wp_query = null; to //$wp_query = null;\n</code></pre>\n"
}
] |
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/functions/get_search_form/\" rel=\"nofollow\"><code>get_search_form()</code></a> function:</p>\n\n<pre><code><?php get_search_form(); ?>\n</code></pre>\n\n<p><code>get_search_form()</code> will use a default HTML form, but you can create your own custom form by adding a <code>searchform.php</code> file to your theme.</p>\n"
},
{
"answer_id": 242919,
"author": "Raunak Gupta",
"author_id": 103815,
"author_profile": "https://wordpress.stackexchange.com/users/103815",
"pm_score": 0,
"selected": false,
"text": "<p>You can add this HTML form to your page</p>\n\n<pre><code><form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"<?php echo esc_url( home_url( '/' ) ); ?>\">\n <div>\n <label class=\"screen-reader-text\" for=\"s\"><?php _x( 'Search for:', 'label' ); ?></label>\n <input type=\"text\" value=\"<?php echo get_search_query(); ?>\" name=\"s\" id=\"s\" class=\"banner-text-box\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"<?php echo esc_attr_x( 'Search', 'submit button' ); ?>\" class=\"banner-text-btn\"/>\n </div>\n</form>\n</code></pre>\n\n<hr>\n\n<p>Refrence:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_search_form/#user-contributed-notes\" rel=\"nofollow\">Default HTML Form</a></li>\n</ul>\n"
}
] |
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/functions/get_search_form/\" rel=\"nofollow\"><code>get_search_form()</code></a> function:</p>\n\n<pre><code><?php get_search_form(); ?>\n</code></pre>\n\n<p><code>get_search_form()</code> will use a default HTML form, but you can create your own custom form by adding a <code>searchform.php</code> file to your theme.</p>\n"
},
{
"answer_id": 242919,
"author": "Raunak Gupta",
"author_id": 103815,
"author_profile": "https://wordpress.stackexchange.com/users/103815",
"pm_score": 0,
"selected": false,
"text": "<p>You can add this HTML form to your page</p>\n\n<pre><code><form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"<?php echo esc_url( home_url( '/' ) ); ?>\">\n <div>\n <label class=\"screen-reader-text\" for=\"s\"><?php _x( 'Search for:', 'label' ); ?></label>\n <input type=\"text\" value=\"<?php echo get_search_query(); ?>\" name=\"s\" id=\"s\" class=\"banner-text-box\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"<?php echo esc_attr_x( 'Search', 'submit button' ); ?>\" class=\"banner-text-btn\"/>\n </div>\n</form>\n</code></pre>\n\n<hr>\n\n<p>Refrence:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_search_form/#user-contributed-notes\" rel=\"nofollow\">Default HTML Form</a></li>\n</ul>\n"
}
] |
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 look over it and I've adapted my new query like so:</p>\n\n<pre><code>$category_slug = filter_input(\n INPUT_GET,\n 'eventtype',\n FILTER_SANITIZE_STRING\n);\n\n$cat_query = [];\nif( $event_type ){\n $cat_query = [\n [\n 'taxonomy' => 'eventtype',\n 'field' => 'slug',\n 'terms' => $event_type\n\n ]\n ];\n}\n\n$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n$args = array(\n 'post_type' => array('whatson'),\n 'post_status' => 'publish',\n 'tax_query' => $cat_query,\n 'meta_query' => array(\n\n array(\n 'key' => 'sc_related_venues_title',\n 'value' => $location,\n 'compare' => 'LIKE' ,\n 'field' => 'title',\n ),\n ),\n 'orderby' => 'date',\n 'order' => 'desc',\n 'posts_per_page' => '10',\n 'paged' => $paged,\n);\n$wp_query = new WP_Query( $args);\n</code></pre>\n"
},
{
"answer_id": 242941,
"author": "Khorshed Alam",
"author_id": 104420,
"author_profile": "https://wordpress.stackexchange.com/users/104420",
"pm_score": 0,
"selected": false,
"text": "<p>Try after removing <code>'compare' => 'LIKE'</code> from <code>tax_query</code>.</p>\n\n<p><code>tax_query</code> doesn't have the param <code>compare</code> it's available for <code>meta_query</code></p>\n\n<pre><code>'tax_query' => array(\n array(\n 'taxonomy' => 'eventtype',\n 'terms' => $event_type,\n 'field' => 'slug',\n )\n),\n</code></pre>\n"
},
{
"answer_id": 242946,
"author": "bagpipper",
"author_id": 80397,
"author_profile": "https://wordpress.stackexchange.com/users/80397",
"pm_score": 0,
"selected": false,
"text": "<p>Since you are already using slug to compare your taxonomy.\nTry with </p>\n\n<pre><code>$wp_query = new WP_Query( array(\n 'post_type' => 'whatson',\n 'post_status' => 'publish',\n 'eventtype' => $event_type,\n 'meta_query' => array(\n array(\n 'key' => 'sc_related_venues_title',\n 'value' => $location,\n 'compare' => 'LIKE' ,\n 'field' => 'title',\n ),\n ),\n 'posts_per_page' => '10',\n 'paged' => $paged\n ) );\n</code></pre>\n"
},
{
"answer_id": 279795,
"author": "Hardik Amipara",
"author_id": 127730,
"author_profile": "https://wordpress.stackexchange.com/users/127730",
"pm_score": -1,
"selected": false,
"text": "<p>try belwo code for meta query and tax_query.</p>\n\n<pre><code><?php\n$category_object=get_queried_object();\n$term_id = $category_object->term_id;\n$name = $category_object->name;\n$description = $category_object->description;\n\n$wp_query = new WP_Query( array(\n 'post_type' => 'whatson',\n 'post_status' => 'publish',\n 'meta_query' => array(\n 'relation' => 'AND',\n array(\n 'key' => 'sc_related_venues_title',\n 'value' => $location,\n 'compare' => 'LIKE',\n 'field' => 'title',\n ),\n ),\n 'tax_query' => array(\n array(\n 'taxonomy' => 'eventtype',\n 'field' => 'id',\n 'terms' => $term_id\n )\n ),\n 'posts_per_page' => '10',\n 'paged' => $paged\n) );\n?>\n</code></pre>\n"
}
] |
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 respect to <code>0</code> and with operator <code>===</code>. That means the returned value of the <code>preg_match</code> function has to be <code>(int) 0</code> or <code>(string) 0</code>. And after that it is checking if <code>$_REQUEST['author']</code> is empty or not.</p>\n\n<p>And in <strong>Logic #2</strong> is checking the same thing above, but with <code>!()</code>(not) operator. And this method also additionally check the <code>$_REQUEST['author']</code> is <code>integer</code> or not. </p>\n\n<p>Checking the <code>$_REQUEST['author']</code> data type actually makes <strong>Logic #2</strong> better than above <strong>Logic #1</strong>, I think. Cause, though data type doesn't matter in <code>PHP</code> (<code>PHP</code> 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.</p>\n\n<p>Hope that answer satisfies your quest.</p>\n"
},
{
"answer_id": 243029,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>off-topic but probably worth mentioning - there is a different solution to the issue and this is to change the user slug to be different than the login name, for example. this can be some random variation that can be overriden for actual authors that actually have something on their pages.</p>\n\n<p>In any case I am not a great believer in redirecting to random locations (why home page?). If you want to \"disable\" the URl serve a 404 page.</p>\n\n<p>... and <code>$_REQUEST</code> is way too broad, and may trigger redirect on ajax request and cookies. You should care only about the URL parameter so better to probably stick with <code>$_GET</code> </p>\n"
},
{
"answer_id": 243296,
"author": "klewis",
"author_id": 98671,
"author_profile": "https://wordpress.stackexchange.com/users/98671",
"pm_score": 0,
"selected": false,
"text": "<p>If for some reason you want your security to be processed through an official plugin with the ability to disable author pages, as well a 301,307, and destination page redirect options, then try out...</p>\n\n<p><a href=\"https://wordpress.org/plugins/disable-author-pages/\" rel=\"nofollow\">Disable Author Pages</a></p>\n\n<p>I'm currently testing it out on WP version 4.6.1 and it works.</p>\n"
}
] |
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 use <code>post_type_link</code> instead.</p>\n\n<pre><code>/**\n * replace the '%item%' tag with the first \n * term slug in the item taxonomy\n * \n * @wp-hook post_link\n * @param string $permalink\n * @param WP_Post $post\n * @return string\n */\nadd_filter( 'post_type_link', 'wpse_56769_post_link', 10, 2 );\nfunction wpse_56769_post_link( $permalink, $post ) {\n\n if( $post->post_type == 'product' ) {\n $default_term = 'no_item';\n $terms = wp_get_post_terms( $post->ID, 'item' );\n\n if ( ! empty( $terms ) && ! is_wp_error( $terms ) )\n $term = current( $terms )->slug;\n else\n $term = $default_term;\n\n $permalink = str_replace( '%item%', $term, $permalink );\n }\n\n return $permalink;\n}\n</code></pre>\n"
},
{
"answer_id": 316068,
"author": "RCNeil",
"author_id": 12294,
"author_profile": "https://wordpress.stackexchange.com/users/12294",
"pm_score": 0,
"selected": false,
"text": "<p>I used this very helpful answer for WooCommerce Product Vendors, as I wanted the Vendor in the Permalink. Below is a modified condensed snippet to do just that in your <code>functions.php</code> file.</p>\n\n<pre><code>//VENDOR PERMALINK\nadd_filter( 'post_type_link', 'wpse_56769_post_link', 10, 2 );\nfunction wpse_56769_post_link( $permalink, $post ) {\n if( $post->post_type == 'product' ) {\n $default_term = 'vendor';\n $terms = wp_get_post_terms( $post->ID, 'wcpv_product_vendors' );\n if ( ! empty( $terms ) && ! is_wp_error( $terms ) )\n $term = current( $terms )->slug;\n else\n $term = $default_term;\n $permalink = str_replace( '%wcpv_product_vendors%', $term, $permalink );\n }\n return $permalink;\n}\nfunction wpse_56769_rewrite_verbose_page_rules( $pass_through = NULL ) {\n $permastruct = $GLOBALS[ 'wp_rewrite' ]->permalink_structure;\n $permastruct = trim( $permastruct, '/%' );\n if ( 0 !== strpos( $permastruct, 'wcpv_product_vendors%' ) )\n return $pass_through;\n $GLOBALS[ 'wp_rewrite' ]->use_verbose_page_rules = TRUE;\n return $pass_through;\n}\nadd_filter( 'page_rewrite_rules', 'wpse_56769_rewrite_verbose_page_rules', \nPHP_INT_MAX );\nadd_filter( 'do_parse_request', 'wpse_56769_rewrite_verbose_page_rules', \nPHP_INT_MAX );\nfunction wpse_56769_request_vars( $request_vars ) {\n if ( ! isset( $request_vars[ 'wcpv_product_vendors' ] ) )\n return $request_vars;\n if ( ! isset( $request_vars[ 'name' ] ) )\n return $request_vars;\n if ( 'no_item' == $request_vars[ 'wcpv_product_vendors' ] )\n unset( $request_vars[ 'wcpv_product_vendors' ] );\n return $request_vars;\n}\nadd_filter( 'request', 'wpse_56769_request_vars' );\n</code></pre>\n\n<p>Then you would put the tag <code>%wcpv_product_vendors%</code> in the permalinks settings where you want it. </p>\n\n<p>Thanks to the OP @INT for the very helpful answer and doing all the leg work! </p>\n"
}
] |
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 as a link to www.example.com/myfile.pdf.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 243060,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 0,
"selected": false,
"text": "<p>You can upload the file to the media library and then get the link from there. At that point, you can drop the link into the WordPress menu system or anywhere else you need.</p>\n"
}
] |
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>\n\n<pre><code>add_action( 'admin_init', 'the_dramatist_debug_admin_menu' );\n\nfunction the_dramatist_debug_admin_menu() {\n\n echo '<pre>' . print_r( $GLOBALS[ 'menu' ], TRUE) . '</pre>';\n}\n</code></pre>\n\n<p>Then search for the <code>plugin-slug</code>. In which array you find it copy the <code>[2]</code> value and put it in <code>remove_menu_page('the [2] value')</code> and hook it to <code>admin_init</code> like below-</p>\n\n<pre><code>add_action('admin_init', '');\nfunction the_dramatist_remove_menu(){\n remove_menu_page( 'the [2] value' );\n});\n</code></pre>\n\n<p>And it will be working. And after it is working remove the temporary code block.</p>\n\n<p>On the other hand, you can inspect the plugin code which menu page you wanna remove and in their <code>add_menu_page()</code> function take the fourth parameter of the <code>add_menu_page()</code> function and put it inside <code>remove_menu_page('fourth parameter')</code>. It will work as well. The code will look like below-</p>\n\n<pre><code>add_action('admin_init', '');\nfunction the_dramatist_remove_menu(){\n remove_menu_page( 'fourth parameter of add_menu_page()' );\n});\n</code></pre>\n"
},
{
"answer_id": 243143,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 4,
"selected": true,
"text": "<p>Thanks to the answer that <a href=\"https://wordpress.stackexchange.com/users/44192\">the_dramatist</a> posted, it was a matter of just hooking to the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init\" rel=\"nofollow noreferrer\"><code>admin_init</code></a> 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 <code>admin.php?page=plugin-slug</code>:</p>\n<pre><code>add_action( 'admin_menu', 'wpse_243070_hide_menu' );\n\nfunction wpse_243070_hide_menu() {\n remove_menu_page( 'index.php' ); // Dashboard\n remove_menu_page( 'tools.php' ); // Tools\n remove_menu_page( 'plugin-slug' ); // Some plugin\n remove_menu_page( 'another_slug' ); // Another plugin\n}\n</code></pre>\n"
},
{
"answer_id": 324619,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 1,
"selected": false,
"text": "<p>For me simple unsetting of menu elements proved to be the easiest and most versatile approach, this way you can for instance remove all menu items but leave only some desired like so:</p>\n\n<pre><code>add_filter('admin_menu', 'wpse_243070_hide_menu_items', 100);\n\nfunction wpse_243070_hide_menu_items() {\n foreach ($GLOBALS['menu'] as $mkey => $mval) {\n if (!in_array($mval[2], [\n 'separator1',\n 'separator2',\n 'profile.php',\n 'edit.php?post_type=my_custom_post'\n ])) {\n unset($GLOBALS['menu'][$mkey]);\n }\n }\n}\n</code></pre>\n"
}
] |
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\">after_setup_theme</a> hook is actually an action hook not a filter hook. Nonetheless that should not be needed.</p>\n\n<p>Give this a try:</p>\n\n<pre><code>if( ! function_exists( 'get_field' ) ) {\n function get_field( $key, $post_id = false, $format_value = true ) {\n if( false === $post_id ) {\n global $post;\n $post_id = $post->ID;\n }\n\n return get_post_meta( $post_id, $key, true );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 244314,
"author": "Faisal Khurshid",
"author_id": 45269,
"author_profile": "https://wordpress.stackexchange.com/users/45269",
"pm_score": 2,
"selected": true,
"text": "<p>The issue has been solved. It seems ACF plugin defined <code>get_field()</code> function is not able to override the theme defined <code>get_field()</code> function on ACF plugin activation. Therefore, it throws <code>Fatal error: Cannot redeclare get_field(</code>) error if we use the following code:</p>\n\n<pre><code>if ( !function_exists('get_field') ) {\n\n function get_field($key) {\n return get_post_meta(get_the_ID(), $key, true);\n }\n}\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>if ( !is_admin() && !function_exists('get_field') ) {\n\n function get_field($key) {\n return get_post_meta(get_the_ID(), $key, true);\n }\n\n}\n</code></pre>\n\n<p>Now, our backend is not aware of our custom defined <code>get_field()</code> function so it won't cause any issue while activating the plugin and after activating the plugin the ACF plugin's <code>get_field()</code> function will take over as expected.</p>\n"
},
{
"answer_id": 313807,
"author": "Xavier Serrano",
"author_id": 24921,
"author_profile": "https://wordpress.stackexchange.com/users/24921",
"pm_score": 0,
"selected": false,
"text": "<p>this answers are not good. as get_field does a lot more than getting post_meta it also gets options. best bet is for you to shim the get_field function from core into the theme using the <code>if ( !is_admin() && !function_exists('get_field') ) {}</code> you may have to modify certain things the function is doing such as calling other acf hooks and functions. My preferred options is to not use get_field and use the wp core functions to get the post, comment,user meta and the get_option function. it will decouple your front end from the plugin as well as speed it up.</p>\n"
}
] |
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\">after_setup_theme</a> hook is actually an action hook not a filter hook. Nonetheless that should not be needed.</p>\n\n<p>Give this a try:</p>\n\n<pre><code>if( ! function_exists( 'get_field' ) ) {\n function get_field( $key, $post_id = false, $format_value = true ) {\n if( false === $post_id ) {\n global $post;\n $post_id = $post->ID;\n }\n\n return get_post_meta( $post_id, $key, true );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 244314,
"author": "Faisal Khurshid",
"author_id": 45269,
"author_profile": "https://wordpress.stackexchange.com/users/45269",
"pm_score": 2,
"selected": true,
"text": "<p>The issue has been solved. It seems ACF plugin defined <code>get_field()</code> function is not able to override the theme defined <code>get_field()</code> function on ACF plugin activation. Therefore, it throws <code>Fatal error: Cannot redeclare get_field(</code>) error if we use the following code:</p>\n\n<pre><code>if ( !function_exists('get_field') ) {\n\n function get_field($key) {\n return get_post_meta(get_the_ID(), $key, true);\n }\n}\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>if ( !is_admin() && !function_exists('get_field') ) {\n\n function get_field($key) {\n return get_post_meta(get_the_ID(), $key, true);\n }\n\n}\n</code></pre>\n\n<p>Now, our backend is not aware of our custom defined <code>get_field()</code> function so it won't cause any issue while activating the plugin and after activating the plugin the ACF plugin's <code>get_field()</code> function will take over as expected.</p>\n"
},
{
"answer_id": 313807,
"author": "Xavier Serrano",
"author_id": 24921,
"author_profile": "https://wordpress.stackexchange.com/users/24921",
"pm_score": 0,
"selected": false,
"text": "<p>this answers are not good. as get_field does a lot more than getting post_meta it also gets options. best bet is for you to shim the get_field function from core into the theme using the <code>if ( !is_admin() && !function_exists('get_field') ) {}</code> you may have to modify certain things the function is doing such as calling other acf hooks and functions. My preferred options is to not use get_field and use the wp core functions to get the post, comment,user meta and the get_option function. it will decouple your front end from the plugin as well as speed it up.</p>\n"
}
] |
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 thumbnail to hard crop without creating any other image sizes you are ensuring that there won't be a srcset. </p>\n\n<p>You might find my answer <a href=\"https://wordpress.stackexchange.com/a/241906/94267\">here</a> helpful. </p>\n\n<p>Briefly, in your case, adding this line:</p>\n\n<pre><code>add_image_size ( 'double-size', 1270, 400, true );\n</code></pre>\n\n<p>... will make a srcset with both the cropped sizes when you upload a fresh image larger than 1270x400. </p>\n"
},
{
"answer_id": 243302,
"author": "Charles Xavier",
"author_id": 101716,
"author_profile": "https://wordpress.stackexchange.com/users/101716",
"pm_score": -1,
"selected": false,
"text": "<p>You can create a css class and use this with any height or weight</p>\n\n<pre><code> <div class=\"pbheader\" style=\"background-image:url('<?=get_post_image_url(); ?>')\"></div>\n\n<style>\n.pbheader {\n position: relative;\n background-size: 100%;\n height: 260px;\n background-position: left;\n background-repeat: no-repeat;\n}\n</style>\n</code></pre>\n"
}
] |
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\">Navigational Menu</a> in Wordpress. This way your client can add new terms to the custom menu in the order they so choose it will be reflected as such on your page. </p>\n\n<p>Create a new custom menu in your <code>functions.php</code> file,</p>\n\n<pre><code>function register_my_menu() {\n register_nav_menu('product-list-menu',__( 'Product Listing' ));\n}\nadd_action( 'init', 'register_my_menu' );`\n</code></pre>\n\n<p>Then go to your dashboard menu section, Appearance->Menu, and add your custom taxonomy terms or sub-category terms in the order you wish to list them. (Here is a <a href=\"http://justintadlock.com/archives/2010/06/01/goodbye-headaches-hello-menus\" rel=\"nofollow\">tutorial</a> if you need more info).</p>\n\n<p>Finally you can display your menu on your page as a list, using </p>\n\n<pre><code><?php wp_nav_menu( array( 'theme_location' => 'product-list-menu' ) ); ?>\n</code></pre>\n\n<p>the <code>wp_nav_menu</code> function (<a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow\">codex documentation</a>) allows you to add your own css class to custom style your list. </p>\n\n<p>Wordpress uses a <a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow\">Walker class</a> to build menus. Building each item as a list. You can hook into the default Walker class, using the <code>nav_menu_link_attributes</code> (<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_link_attributes\" rel=\"nofollow\">codex documentation</a>) to customise the html attributes for each menu item, and the <code>wp_nav_menu_items</code> to add custom items at the end of the menu list (<a href=\"http://www.wpbeginner.com/wp-themes/how-to-add-custom-items-to-specific-wordpress-menus/\" rel=\"nofollow\">tutorial</a>).</p>\n\n<p>If you want even more control over the way your list is created (for example use <code><h2></code> tags for your term names, then use a <a href=\"https://code.tutsplus.com/tutorials/understanding-the-walker-class--wp-25401\" rel=\"nofollow\">custom Walker class</a> which you can parse to the function. Having your own Walker class can make for rather powerful functionality, for example if new terms are added to your taxonomy and these have not been added to your menu, then you can verify this at the time of building the list, allowing you to add new items which have not been ordered at the end of the list.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 243226,
"author": "Aurovrata",
"author_id": 52120,
"author_profile": "https://wordpress.stackexchange.com/users/52120",
"pm_score": 0,
"selected": false,
"text": "<p>I am adding another answer here for your information which is quite different from the first one I provided, hence for clarity I am putting it as 2nd answer.</p>\n\n<p>You can use a plugin to order terms within taxonomies. I cam across the <a href=\"https://wordpress.org/plugins/custom-taxonomy-order-ne/\" rel=\"nofollow\">Custom Taxonomy Order New Edition</a> in an article recently which I am yet to try. Searching on google I also came across the <a href=\"https://wordpress.org/plugins/taxonomy-terms-order/\" rel=\"nofollow\">Category Order and Taxonomy Terms Order</a> which seems to be doing something similar. You might want to give these a spin to see if they meet your needs.</p>\n"
},
{
"answer_id": 370724,
"author": "Kojaks",
"author_id": 158425,
"author_profile": "https://wordpress.stackexchange.com/users/158425",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n<p>The solution turned out to be quite simple.</p>\n<p>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.</p>\n"
}
] |
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\">Navigational Menu</a> in Wordpress. This way your client can add new terms to the custom menu in the order they so choose it will be reflected as such on your page. </p>\n\n<p>Create a new custom menu in your <code>functions.php</code> file,</p>\n\n<pre><code>function register_my_menu() {\n register_nav_menu('product-list-menu',__( 'Product Listing' ));\n}\nadd_action( 'init', 'register_my_menu' );`\n</code></pre>\n\n<p>Then go to your dashboard menu section, Appearance->Menu, and add your custom taxonomy terms or sub-category terms in the order you wish to list them. (Here is a <a href=\"http://justintadlock.com/archives/2010/06/01/goodbye-headaches-hello-menus\" rel=\"nofollow\">tutorial</a> if you need more info).</p>\n\n<p>Finally you can display your menu on your page as a list, using </p>\n\n<pre><code><?php wp_nav_menu( array( 'theme_location' => 'product-list-menu' ) ); ?>\n</code></pre>\n\n<p>the <code>wp_nav_menu</code> function (<a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow\">codex documentation</a>) allows you to add your own css class to custom style your list. </p>\n\n<p>Wordpress uses a <a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow\">Walker class</a> to build menus. Building each item as a list. You can hook into the default Walker class, using the <code>nav_menu_link_attributes</code> (<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_link_attributes\" rel=\"nofollow\">codex documentation</a>) to customise the html attributes for each menu item, and the <code>wp_nav_menu_items</code> to add custom items at the end of the menu list (<a href=\"http://www.wpbeginner.com/wp-themes/how-to-add-custom-items-to-specific-wordpress-menus/\" rel=\"nofollow\">tutorial</a>).</p>\n\n<p>If you want even more control over the way your list is created (for example use <code><h2></code> tags for your term names, then use a <a href=\"https://code.tutsplus.com/tutorials/understanding-the-walker-class--wp-25401\" rel=\"nofollow\">custom Walker class</a> which you can parse to the function. Having your own Walker class can make for rather powerful functionality, for example if new terms are added to your taxonomy and these have not been added to your menu, then you can verify this at the time of building the list, allowing you to add new items which have not been ordered at the end of the list.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 243226,
"author": "Aurovrata",
"author_id": 52120,
"author_profile": "https://wordpress.stackexchange.com/users/52120",
"pm_score": 0,
"selected": false,
"text": "<p>I am adding another answer here for your information which is quite different from the first one I provided, hence for clarity I am putting it as 2nd answer.</p>\n\n<p>You can use a plugin to order terms within taxonomies. I cam across the <a href=\"https://wordpress.org/plugins/custom-taxonomy-order-ne/\" rel=\"nofollow\">Custom Taxonomy Order New Edition</a> in an article recently which I am yet to try. Searching on google I also came across the <a href=\"https://wordpress.org/plugins/taxonomy-terms-order/\" rel=\"nofollow\">Category Order and Taxonomy Terms Order</a> which seems to be doing something similar. You might want to give these a spin to see if they meet your needs.</p>\n"
},
{
"answer_id": 370724,
"author": "Kojaks",
"author_id": 158425,
"author_profile": "https://wordpress.stackexchange.com/users/158425",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n<p>The solution turned out to be quite simple.</p>\n<p>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.</p>\n"
}
] |
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 and 2 optionals. In your case, it's better to use to $selected and $current.</p>\n\n<p>You miss the underscore before your meta-field name in the select name.</p>\n\n<p>For selected():</p>\n\n<pre><code>selected( $selected, $current, $echo);\n</code></pre>\n\n<p>you can read more about this from the codex <a href=\"https://codex.wordpress.org/Function_Reference/selected\" rel=\"nofollow\">function reference selected()</a></p>\n\n<p>Your select must be like this:</p>\n\n<pre><code><select name=\"_menu-item-content-multiple[]\" multiple>\n <?php \n foreach ($select_options as $key => $value) {\n echo '<option value=\"'.$key.'\" '.selected(in_array($key, $item->content_multiple), $key).'>'.$value.'</option>';\n }\n ?>\n</select>\n</code></pre>\n"
},
{
"answer_id": 243246,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 6,
"selected": true,
"text": "<p>You do this:</p>\n\n<pre><code>$item->content_multiple = get_post_meta($item->ID, '_menu_item_content_multiple', true);\n</code></pre>\n\n<p>Note how you set the third parameter of <code>get_post_meta()</code> to <code>true</code>, which means that only one value will be returned. <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"noreferrer\">If you read the docs</a>, you will see that, if the third parameter is <code>false</code>, you will get an <strong>array</strong> with all the values for that meta field.</p>\n\n<p>Remember that meta fields can be unique or can be multiple. Or it can be unique with a serialized data string.</p>\n\n<p>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 <strong>converts it to a serialized string before it is stored in the database</strong>; this is done internally with the function <code>maybe_serialize()</code>. Then, when you try to get the value of the meta field, if it is a serialized string, WordPress pass it through <code>maybe_unserialize()</code>, so the serialized string converts back to the array:</p>\n\n<p>Let's explain with a generic example.</p>\n\n<p>This will be the array of values to be stored in the database:</p>\n\n<pre><code>$values = [ 'red', 'yellow', 'blue', 'pink' ];\n</code></pre>\n\n<p>If your meta key is \"color\", the you have two options:</p>\n\n<h2>Multiple entries for the same meta key</h2>\n\n<pre><code>$values = [ 'red', 'yellow', 'blue', 'pink' ];\nforeach( $values as $value ) {\n // This method uses `add_post_meta()` instead of `update_post_meta()`\n add_post_meta( $item_id, 'color', $value );\n}\n</code></pre>\n\n<p>Now, the item identified with <code>$item_id</code> will have several entries for the <code>color</code> meta key. Then, you can use <code>get_post_meta()</code> with the third parameter set to <code>false</code> and you will get an array with all the values:</p>\n\n<pre><code>// You don't really need the set the third parameter\n// because it is false vay default\n$colors = get_post_meta( $item_id, 'color' );\n\n// $colors should an array with all the meta values for the color meta key\nvar_dump( $colors );\n</code></pre>\n\n<h2>Store the array in a single meta entry</h2>\n\n<p>In this case, the array of values is serialized before it is sotred in database:</p>\n\n<pre><code>$values = [ 'red', 'yellow', 'blue', 'pink' ];\n// WordPress does this automatically when an array is passed as meta value\n// $values = maybe_serialize( $values );\nupdate_post_meta( $item_id, 'color', $values );\n</code></pre>\n\n<p>Now, the item identified with <code>$item_id</code> will have only one entry for the <code>color</code> meta key; the value is a serialized string representing the original array. Then, you can use <code>get_post_meta()</code>, with the third parameter set to true, as you have only one entry, and then unserialize the string to get back the array:</p>\n\n<pre><code>$colors = get_post_meta( $item_id, 'color', true );\n// WordPress does this automatically when the meta value is a serialized array\n// $colors = maybe_unserialize( $colors );\n\n// $colors should be an array\nvar_dump( $colors );\n</code></pre>\n\n<p>You can follow the same approach with the select multiple of your form.</p>\n\n<p><strong>With only one entry for the meta key:</strong></p>\n\n<pre><code>if( ! empty( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) ) {\n $meta_field_value = $_REQUEST['menu-item-content-multiple'][$menu_item_db_id];\n // $meta_field_value will be serialized automatically by WordPress\n update_post_meta( $menu_item_db_id, '_menu_item_content_multiple', $meta_field_value );\n}\n</code></pre>\n\n<p>Then, you can use the value as array:</p>\n\n<pre><code> // The value returned by get_post_meta() is unserialized automatically by WordPress\n $item->content_multiple = get_post_meta( $item->ID, '_menu_item_content_multiple', true );\n</code></pre>\n\n<p><strong>With multiple entries:</strong></p>\n\n<p>The concept here is a bit different; you will several entries in the database with the same meta key, so you need to use <code>add_post_meta()</code> instead of <code>update_post_meta()</code> in order to add a new entry for each value.</p>\n\n<pre><code>if( ! empty( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) ) {\n $values = $_REQUEST[ 'menu-item-content-multiple' . $menu_item_db_id ];\n foreach( $values as $value ) {\n add_post_meta( $menu_item_db_id, '_menu_item_content_multiple', $value );\n }\n}\n</code></pre>\n\n<p>Now, you can use <code>get_post_meta()</code> with the third parameter set to <code>false</code> (it is the default value, so you can omit it):</p>\n\n<pre><code>$item->content_multiple = get_post_meta( $item->ID, '_menu_item_content_multiple', false );\n</code></pre>\n\n<p>Both options are OK, you must decide which one is better to organize the data within your project.</p>\n\n<p><strong>Side note</strong>: you should do some santization before using the input data, but I don't know the requirements for you, here a example:</p>\n\n<pre><code>array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) );\n</code></pre>\n"
}
] |
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 plugin, then use filters to override in the theme, e.g.</p>\n\n<p>In the plugins:</p>\n\n<pre><code>function my_awesome_function() {\n return apply_filters( 'my_awesome_function', \"plugin\" );\n}\n</code></pre>\n\n<p>In your theme:</p>\n\n<pre><code>add_filter( 'my_awesome_function', function( $value ) {\n return \"theme\";\n} );\n</code></pre>\n\n<p>Now every call to <code>my_awesome_function();</code> will return \"theme\" not \"plugin\"</p>\n"
},
{
"answer_id": 243248,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>When the function is loading, the second function is not yet called. So the function_exist check for a function that has not been registered yet. When the second one is loading the first one has been already called and then exist and create the fatal error.</p>\n\n<p>If your awesome function without the function_exists is in a child theme or a plugin file, I think you better invert function_exists check for the second one.</p>\n"
},
{
"answer_id": 243257,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>1) if you write a theme don't eve use <code>function_exists</code>, use proper filter instead.</p>\n\n<p>2) Your problem comes from different order of execution when activating a plugin. Usually the plugin is included before the theme, but in that case it is included after the theme</p>\n\n<p>The proper way to write your plugin code is</p>\n\n<pre><code>if ( ! function_exists( 'my_awesome_function' ) ) {\n function my_awesome_function() {\n return \"plugin\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 243264,
"author": "Niels van Renselaar",
"author_id": 67313,
"author_profile": "https://wordpress.stackexchange.com/users/67313",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should wrap it in a hook. There are different execution times for different things in themes and plugins. If you hook into the right hook your code get executed before the functions of the theme is loaded. For a list of the hooks, check the codex:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference</a></p>\n\n<p>Find the appropiate one that works for you. If the theme has it all wrapped in \"function_exists\" then that should work.</p>\n"
}
] |
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 \"filter\" out private pages for non-logged-in users).</p>\n\n<p>Just get the post and do with it as you wish:</p>\n\n<pre><code>if ( $my_page = get_post( 1457 ) ) {\n setup_postdata( $GLOBALS['post'] = $my_page );\n // Whatever you need to do\n wp_reset_postdata();\n}\n</code></pre>\n"
},
{
"answer_id": 243278,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p><code>setup_postdata</code> takes a post object of type <code>\\WP_Post</code>, but you're passing it a <code>WP_Query</code> instead</p>\n\n<p>e.g.</p>\n\n<pre><code>global $post;\nsetup_postdata( $post );\n</code></pre>\n\n<p>Thankfully the solution is trivial, when you call <code>the_post</code>, it sets up the current post data for you, so removing that line is all you need to do.</p>\n\n<p>The second issue is that <code>WP_Query</code> will filter out private posts if you're not logged in, so setting the post status to private is necessary.</p>\n\n<p>An important thing you're missing though is the clean up call. You need to call <code>wp_reset_postdata()</code> when you're done so that code that runs after your loop has the current post and not the last post in your query.</p>\n\n<p>Here's what that query might look like:</p>\n\n<pre><code>$the_query = new WP_Query( array(\n 'id' => '1457'\n 'post_type' => 'page',\n 'post_status' => 'private'\n) );\nif ( $the_query->have_posts() ) {\n while( $the_query->have_posts() ) {\n $the_query->the_post();\n // do something;\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>There's a faster way though, you already know the post ID, so we can do this:</p>\n\n<pre><code>$p = get_post( 1457 );\nif ( null !== $p ) {\n setup_postdata( $p );\n // do things\n wp_reset_postdata();\n}\n</code></pre>\n"
}
] |
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-</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'the_dramatist_admin_styles' );\nfunction the_dramatist_admin_styles() {\n wp_enqueue_style( 'admin-css-override', get_template_directory_uri() . '/your-admin-css-file.css', false );\n} \n</code></pre>\n\n<p>And put your admin <code>css</code> code there. As your code above the inside of <code>your-admin-css-file.css</code> will look kinda like-</p>\n\n<pre><code>.wp-full-overlay.expanded {\n margin-left: 500px !important;\n}\n#customize-controls.wp-full-overlay-sidebar {\n width: 500px !important;\n}\n</code></pre>\n\n<p>And it'll work.</p>\n"
},
{
"answer_id": 348750,
"author": "jerclarke",
"author_id": 175,
"author_profile": "https://wordpress.stackexchange.com/users/175",
"pm_score": 0,
"selected": false,
"text": "<h2>Making the customize sidebar a higher percentage of the screen</h2>\n\n<p>The answer by CodeMascot works, but I figured I'd also submit a percentage-based answer, since from what I can tell the current system is mainly maxed-out by percentage of the screen, and it seems like an elegant way to go so that you are less likely to have problems if you use a smaller screen. </p>\n\n<pre><code>/*Wider customizer sidebar based on percentage*/\n/*It will fall back to min-width: 300px*/\n.wp-full-overlay-sidebar {\n width: 22%;\n}\n/*Wider margin on preview to make space for sidebar (match theme)*/\n.wp-full-overlay.expanded {\n margin-left: 22%;\n}\n\n/*Below a certain size we revert to 300px because it's the min-width*/\n/*Calculate this number as 300/% i.e. 300/.22=1363*/\n@media (max-width: 1363px) {\n .wp-full-overlay.expanded {\n margin-left: 300px;\n }\n}\n\n</code></pre>\n\n<p>For me this solved my problem after I tuned the percentage to reflect the widest size the site I'm working on takes up on the screen I'm using. For editing CSS I would have made it even higher if I was working on a site with a smaller max width. </p>\n\n<h2>For bonus points, here's how to enqueue the CSS file if it lives in a plugin rather than the theme</h2>\n\n<p>(if you have it in your theme, see CodeMascot's answer above):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function jer_admin_styles() {\n wp_enqueue_style( 'admin-css-override', plugins_url( \"jer-admin.css\", __FILE__ ) , false );\n} \nadd_action( 'admin_enqueue_scripts', 'jer_admin_styles' );\n</code></pre>\n"
}
] |
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 meta fields \n// from the edit 'excursion' post type page.\nfunction my_exclude_custom_fields( $protected, $meta_key ) {\n\n if ( 'excursion' == get_post_type() ) {\n\n if ( in_array( $meta_key, array( 'included', 'not included' ) ) ) {\n return true;\n }\n\n }\n\n return $protected;\n}\nadd_filter( 'is_protected_meta', 'my_exclude_custom_fields', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 346544,
"author": "AaliyaA Ousama",
"author_id": 174590,
"author_profile": "https://wordpress.stackexchange.com/users/174590",
"pm_score": 0,
"selected": false,
"text": "<p>try this </p>\n\n<pre><code>add_filter('is_protected_meta', 'my_is_protected_meta_filter5', 10, 2);\nfunction my_is_protected_meta_filter5($protected, $meta_key) {\n if ( in_array( $meta_key, array( 'para1', 'para2' ) ) ) {\n return true;\n }\n return $protected;\n}\n</code></pre>\n"
}
] |
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(); ?></h1><span>YOUR CUSTOM CONTENT</span>\n</code></pre>\n"
},
{
"answer_id": 339823,
"author": "Өлзийбат Нансалцог",
"author_id": 159595,
"author_profile": "https://wordpress.stackexchange.com/users/159595",
"pm_score": -1,
"selected": false,
"text": "<p>Please try this </p>\n\n<pre><code>the_title( '<h1 class=\"entry-title\">', 'YOUR CUSTOM CONTENT</h1>' );\n</code></pre>\n"
},
{
"answer_id": 339983,
"author": "Amine Faiz",
"author_id": 66813,
"author_profile": "https://wordpress.stackexchange.com/users/66813",
"pm_score": 1,
"selected": false,
"text": "<p>You can use it that way : </p>\n\n<pre><code>function add_suffix_to_title($title, $id = null){\n if (! is_admin()) {\n return '<h1>'.$title.'</h1> Your Suffix';\n }\n return $title;\n}\n\nadd_action( 'the_title', 'add_suffix_to_title', 10, 1 );\n</code></pre>\n\n<p>And when you invoke the \"the_title\" function remove the h1 tag : </p>\n\n<pre><code>the_title();\n</code></pre>\n\n<p>I hope that would help you.</p>\n"
}
] |
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"
},
{
"answer_id": 243389,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>With the code in the functions.php, are you including all the required Bootstrap assets that are need ? Bootstrap collapse needs css and bootstrap.min.js to properly work.</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.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">register_post_type</a>, you need to add a new argument for 'has_archive'.</p>\n<p>So you'll add in something to the effect of:</p>\n<pre><code>'has_archive' => 'about-cool-post-types'\n</code></pre>\n<p>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.</p>\n"
},
{
"answer_id": 243930,
"author": "RichardTape",
"author_id": 25379,
"author_profile": "https://wordpress.stackexchange.com/users/25379",
"pm_score": 3,
"selected": false,
"text": "<p>There's also a simple, 1-file plugin for this now, by the HumanMade folk;</p>\n\n<p><a href=\"https://github.com/humanmade/page-for-post-type\" rel=\"noreferrer\">https://github.com/humanmade/page-for-post-type</a></p>\n\n<p>(Meta: I know answers with links aren't generally great, but I don't just want to copy and paste the source-code for that thing into an answer. What's the best strategy for this type of thing?)</p>\n"
}
] |
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/Filter_Reference/wp_handle_upload_prefilter\" rel=\"nofollow\">wp_handle_upload_prefilter</a>. Though I'm not sure how you are going to determine if it's a post upload or media upload, maybe you can check the $post global.</p>\n"
},
{
"answer_id": 243386,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 1,
"selected": false,
"text": "<p>The best way of doing this might be to attach a custom field to each post to keep the increment {n}.</p>\n\n<p>Something to the effect of:</p>\n\n<pre><code>$attach_inc = 1;\n\nif ( is_single() ) {\n if ( $attach_inc = get_post_meta( $post_id, 'attachment_inc', true ) ) {\n $attach_inc++;\n update_post_meta( $post_id, 'attachment_inc', $attach_inc );\n } else {\n add_post_meta( $post_id, 'attachment_inc', $attach_inc );\n }\n} else {\n if ( $attach_inc = get_option( 'attachment_inc' ) ) {\n $attach_inc++;\n set_option( 'attachment_inc', $attach_inc );\n } else {\n add_option( 'attachment_inc', $attach_inc );\n }\n}\n\n// DO YOUR ADD ATTACHMENT STUFF HERE\n</code></pre>\n"
}
] |
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 for stuff like the admin bar and are not enqueued if you are not logged in. </p>\n\n<pre><code>function wpdocs_dequeue_script() {\n wp_dequeue_script( 'jquery-ui-core' );\n}\nadd_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );\n</code></pre>\n\n<p>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.</p>\n\n<pre><code><?php global $wp_scripts; var_dump($wp_scripts); ?>\n</code></pre>\n"
},
{
"answer_id": 243421,
"author": "Alex Protopopescu",
"author_id": 104577,
"author_profile": "https://wordpress.stackexchange.com/users/104577",
"pm_score": 2,
"selected": false,
"text": "<p>This will do the trick for you, assuming that you don't have any custom extra assets loading from the /wp-admin/ directory in the frontend.</p>\n\n<p>It takes the $wp_scripts and $wp_styles globals, iterates through the registered resources and deregisteres the resources which have a source directory not containing '/wp-admin/'.</p>\n\n<pre><code>function my_deregister_scripts_and_styles() {\n global $wp_scripts, $wp_styles;\n\n foreach($wp_scripts->registered as $registered)\n if(strpos($registered->src,'/wp-admin/')===FALSE)\n wp_deregister_script($registered->handle);\n\n foreach($wp_styles->registered as $registered)\n if(strpos($registered->src,'/wp-admin/')===FALSE)\n wp_deregister_style($registered->handle);\n}\nadd_action( 'wp_enqueue_scripts', 'my_deregister_scripts_and_styles');\n</code></pre>\n"
},
{
"answer_id": 366261,
"author": "gtamborero",
"author_id": 52236,
"author_profile": "https://wordpress.stackexchange.com/users/52236",
"pm_score": 0,
"selected": false,
"text": "<p>Is that easy, use dequeue on your functions.php file (inside your active theme). This way I dequeue 4 files:</p>\n\n<pre><code>// DEQUEUE GUTENBERG STYLES FOR FRONT\nfunction my_deregister_scripts_and_styles() {\n wp_deregister_script('wp-util'); //deregister script\n wp_deregister_script('underscore'); \n wp_dequeue_style( 'wp-block-library'); //deregister style\n wp_dequeue_style( 'wc-block-style' ); \n wp_dequeue_style( 'wp-block-library-theme' );\n}\nadd_action( 'wp_enqueue_scripts', 'my_deregister_scripts_and_styles', 999);\n</code></pre>\n\n<p>Try directly the asset name without it's extension (js / css) and if it doesn't work open the html inspector and try to use the id name of the script.\nFor example: <code><link rel='stylesheet' id='resource-special-name' href='https://www.test.com/resource.css' type='text/css' /></code></p>\n\n<p>If it doesn't work, then do a full search of the name (for example: block-style.css) and you will find a call as this:</p>\n\n<pre><code>`wp_enqueue_style( 'block-special-name', get_template_directory_uri() . '/css/vendor/block-style.css', \n</code></pre>\n"
}
] |
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> instead and I think you'll see it added in there. </p>\n\n<p>The way I usually use it is like this:</p>\n\n<pre><code>add_filter( 'query_vars', 'add_test_query_vars');\n\nfunction add_test_query_vars($vars){\n $vars[] = \"test\";\n return $vars;\n}\n</code></pre>\n\n<p>So the same as you but with a named function.</p>\n\n<p>Then I add a rewrite endpoint:</p>\n\n<pre><code>function wpse_243396_endpoint() {\n add_rewrite_endpoint( 'test', EP_PERMALINK );\n}\n\nadd_action( 'init', 'wpse_243396_endpoint' );\n</code></pre>\n\n<p>And after that URLs ending <code>/test/</code> set the query var which I test like this:</p>\n\n<pre><code>global $wp_query; \nif( isset( $wp_query->query['test'] ) ) { }\n</code></pre>\n"
},
{
"answer_id": 354978,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 0,
"selected": false,
"text": "<p>I think the value would only be present if you add the get-param to the url when trying to preview it ( or specifically set a value for the query-var using <code>$query->set()</code> )</p>\n\n<p>Try adding <code>?xyz=hello-world</code> to the end of the url you're testing on & you should see <code>hello-world</code> in the dump. </p>\n\n<p>It will also depend on where you dump... maybe try this:</p>\n\n<pre><code>add_filter('query_vars', function ($vars) {\n $vars[] = 'xyz';\n return $vars;\n});\n</code></pre>\n\n<p>then visit: <code>yoursite.com/?xyz=hello-world</code></p>\n\n<pre><code>function trythis( $wp_query ) {\n if ( $wp_query->is_main_query() && ! is_admin() ) {\n var_dump( $wp_query ); \n exit;\n }\n}\nadd_action( 'pre_get_posts', 'trythis' );\n</code></pre>\n\n<p>... & you should see <code>'xyz'=>'hello-world'</code> in the dump. I don't think query vars are added to wp-query unless they need to be, that'd add unnecessary bloat.</p>\n"
}
] |
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> instead and I think you'll see it added in there. </p>\n\n<p>The way I usually use it is like this:</p>\n\n<pre><code>add_filter( 'query_vars', 'add_test_query_vars');\n\nfunction add_test_query_vars($vars){\n $vars[] = \"test\";\n return $vars;\n}\n</code></pre>\n\n<p>So the same as you but with a named function.</p>\n\n<p>Then I add a rewrite endpoint:</p>\n\n<pre><code>function wpse_243396_endpoint() {\n add_rewrite_endpoint( 'test', EP_PERMALINK );\n}\n\nadd_action( 'init', 'wpse_243396_endpoint' );\n</code></pre>\n\n<p>And after that URLs ending <code>/test/</code> set the query var which I test like this:</p>\n\n<pre><code>global $wp_query; \nif( isset( $wp_query->query['test'] ) ) { }\n</code></pre>\n"
},
{
"answer_id": 354978,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 0,
"selected": false,
"text": "<p>I think the value would only be present if you add the get-param to the url when trying to preview it ( or specifically set a value for the query-var using <code>$query->set()</code> )</p>\n\n<p>Try adding <code>?xyz=hello-world</code> to the end of the url you're testing on & you should see <code>hello-world</code> in the dump. </p>\n\n<p>It will also depend on where you dump... maybe try this:</p>\n\n<pre><code>add_filter('query_vars', function ($vars) {\n $vars[] = 'xyz';\n return $vars;\n});\n</code></pre>\n\n<p>then visit: <code>yoursite.com/?xyz=hello-world</code></p>\n\n<pre><code>function trythis( $wp_query ) {\n if ( $wp_query->is_main_query() && ! is_admin() ) {\n var_dump( $wp_query ); \n exit;\n }\n}\nadd_action( 'pre_get_posts', 'trythis' );\n</code></pre>\n\n<p>... & you should see <code>'xyz'=>'hello-world'</code> in the dump. I don't think query vars are added to wp-query unless they need to be, that'd add unnecessary bloat.</p>\n"
}
] |
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> instead and I think you'll see it added in there. </p>\n\n<p>The way I usually use it is like this:</p>\n\n<pre><code>add_filter( 'query_vars', 'add_test_query_vars');\n\nfunction add_test_query_vars($vars){\n $vars[] = \"test\";\n return $vars;\n}\n</code></pre>\n\n<p>So the same as you but with a named function.</p>\n\n<p>Then I add a rewrite endpoint:</p>\n\n<pre><code>function wpse_243396_endpoint() {\n add_rewrite_endpoint( 'test', EP_PERMALINK );\n}\n\nadd_action( 'init', 'wpse_243396_endpoint' );\n</code></pre>\n\n<p>And after that URLs ending <code>/test/</code> set the query var which I test like this:</p>\n\n<pre><code>global $wp_query; \nif( isset( $wp_query->query['test'] ) ) { }\n</code></pre>\n"
},
{
"answer_id": 354978,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 0,
"selected": false,
"text": "<p>I think the value would only be present if you add the get-param to the url when trying to preview it ( or specifically set a value for the query-var using <code>$query->set()</code> )</p>\n\n<p>Try adding <code>?xyz=hello-world</code> to the end of the url you're testing on & you should see <code>hello-world</code> in the dump. </p>\n\n<p>It will also depend on where you dump... maybe try this:</p>\n\n<pre><code>add_filter('query_vars', function ($vars) {\n $vars[] = 'xyz';\n return $vars;\n});\n</code></pre>\n\n<p>then visit: <code>yoursite.com/?xyz=hello-world</code></p>\n\n<pre><code>function trythis( $wp_query ) {\n if ( $wp_query->is_main_query() && ! is_admin() ) {\n var_dump( $wp_query ); \n exit;\n }\n}\nadd_action( 'pre_get_posts', 'trythis' );\n</code></pre>\n\n<p>... & you should see <code>'xyz'=>'hello-world'</code> in the dump. I don't think query vars are added to wp-query unless they need to be, that'd add unnecessary bloat.</p>\n"
}
] |
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> instead and I think you'll see it added in there. </p>\n\n<p>The way I usually use it is like this:</p>\n\n<pre><code>add_filter( 'query_vars', 'add_test_query_vars');\n\nfunction add_test_query_vars($vars){\n $vars[] = \"test\";\n return $vars;\n}\n</code></pre>\n\n<p>So the same as you but with a named function.</p>\n\n<p>Then I add a rewrite endpoint:</p>\n\n<pre><code>function wpse_243396_endpoint() {\n add_rewrite_endpoint( 'test', EP_PERMALINK );\n}\n\nadd_action( 'init', 'wpse_243396_endpoint' );\n</code></pre>\n\n<p>And after that URLs ending <code>/test/</code> set the query var which I test like this:</p>\n\n<pre><code>global $wp_query; \nif( isset( $wp_query->query['test'] ) ) { }\n</code></pre>\n"
},
{
"answer_id": 354978,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 0,
"selected": false,
"text": "<p>I think the value would only be present if you add the get-param to the url when trying to preview it ( or specifically set a value for the query-var using <code>$query->set()</code> )</p>\n\n<p>Try adding <code>?xyz=hello-world</code> to the end of the url you're testing on & you should see <code>hello-world</code> in the dump. </p>\n\n<p>It will also depend on where you dump... maybe try this:</p>\n\n<pre><code>add_filter('query_vars', function ($vars) {\n $vars[] = 'xyz';\n return $vars;\n});\n</code></pre>\n\n<p>then visit: <code>yoursite.com/?xyz=hello-world</code></p>\n\n<pre><code>function trythis( $wp_query ) {\n if ( $wp_query->is_main_query() && ! is_admin() ) {\n var_dump( $wp_query ); \n exit;\n }\n}\nadd_action( 'pre_get_posts', 'trythis' );\n</code></pre>\n\n<p>... & you should see <code>'xyz'=>'hello-world'</code> in the dump. I don't think query vars are added to wp-query unless they need to be, that'd add unnecessary bloat.</p>\n"
}
] |
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> instead and I think you'll see it added in there. </p>\n\n<p>The way I usually use it is like this:</p>\n\n<pre><code>add_filter( 'query_vars', 'add_test_query_vars');\n\nfunction add_test_query_vars($vars){\n $vars[] = \"test\";\n return $vars;\n}\n</code></pre>\n\n<p>So the same as you but with a named function.</p>\n\n<p>Then I add a rewrite endpoint:</p>\n\n<pre><code>function wpse_243396_endpoint() {\n add_rewrite_endpoint( 'test', EP_PERMALINK );\n}\n\nadd_action( 'init', 'wpse_243396_endpoint' );\n</code></pre>\n\n<p>And after that URLs ending <code>/test/</code> set the query var which I test like this:</p>\n\n<pre><code>global $wp_query; \nif( isset( $wp_query->query['test'] ) ) { }\n</code></pre>\n"
},
{
"answer_id": 354978,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 0,
"selected": false,
"text": "<p>I think the value would only be present if you add the get-param to the url when trying to preview it ( or specifically set a value for the query-var using <code>$query->set()</code> )</p>\n\n<p>Try adding <code>?xyz=hello-world</code> to the end of the url you're testing on & you should see <code>hello-world</code> in the dump. </p>\n\n<p>It will also depend on where you dump... maybe try this:</p>\n\n<pre><code>add_filter('query_vars', function ($vars) {\n $vars[] = 'xyz';\n return $vars;\n});\n</code></pre>\n\n<p>then visit: <code>yoursite.com/?xyz=hello-world</code></p>\n\n<pre><code>function trythis( $wp_query ) {\n if ( $wp_query->is_main_query() && ! is_admin() ) {\n var_dump( $wp_query ); \n exit;\n }\n}\nadd_action( 'pre_get_posts', 'trythis' );\n</code></pre>\n\n<p>... & you should see <code>'xyz'=>'hello-world'</code> in the dump. I don't think query vars are added to wp-query unless they need to be, that'd add unnecessary bloat.</p>\n"
}
] |
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> instead and I think you'll see it added in there. </p>\n\n<p>The way I usually use it is like this:</p>\n\n<pre><code>add_filter( 'query_vars', 'add_test_query_vars');\n\nfunction add_test_query_vars($vars){\n $vars[] = \"test\";\n return $vars;\n}\n</code></pre>\n\n<p>So the same as you but with a named function.</p>\n\n<p>Then I add a rewrite endpoint:</p>\n\n<pre><code>function wpse_243396_endpoint() {\n add_rewrite_endpoint( 'test', EP_PERMALINK );\n}\n\nadd_action( 'init', 'wpse_243396_endpoint' );\n</code></pre>\n\n<p>And after that URLs ending <code>/test/</code> set the query var which I test like this:</p>\n\n<pre><code>global $wp_query; \nif( isset( $wp_query->query['test'] ) ) { }\n</code></pre>\n"
},
{
"answer_id": 354978,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 0,
"selected": false,
"text": "<p>I think the value would only be present if you add the get-param to the url when trying to preview it ( or specifically set a value for the query-var using <code>$query->set()</code> )</p>\n\n<p>Try adding <code>?xyz=hello-world</code> to the end of the url you're testing on & you should see <code>hello-world</code> in the dump. </p>\n\n<p>It will also depend on where you dump... maybe try this:</p>\n\n<pre><code>add_filter('query_vars', function ($vars) {\n $vars[] = 'xyz';\n return $vars;\n});\n</code></pre>\n\n<p>then visit: <code>yoursite.com/?xyz=hello-world</code></p>\n\n<pre><code>function trythis( $wp_query ) {\n if ( $wp_query->is_main_query() && ! is_admin() ) {\n var_dump( $wp_query ); \n exit;\n }\n}\nadd_action( 'pre_get_posts', 'trythis' );\n</code></pre>\n\n<p>... & you should see <code>'xyz'=>'hello-world'</code> in the dump. I don't think query vars are added to wp-query unless they need to be, that'd add unnecessary bloat.</p>\n"
}
] |
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> instead and I think you'll see it added in there. </p>\n\n<p>The way I usually use it is like this:</p>\n\n<pre><code>add_filter( 'query_vars', 'add_test_query_vars');\n\nfunction add_test_query_vars($vars){\n $vars[] = \"test\";\n return $vars;\n}\n</code></pre>\n\n<p>So the same as you but with a named function.</p>\n\n<p>Then I add a rewrite endpoint:</p>\n\n<pre><code>function wpse_243396_endpoint() {\n add_rewrite_endpoint( 'test', EP_PERMALINK );\n}\n\nadd_action( 'init', 'wpse_243396_endpoint' );\n</code></pre>\n\n<p>And after that URLs ending <code>/test/</code> set the query var which I test like this:</p>\n\n<pre><code>global $wp_query; \nif( isset( $wp_query->query['test'] ) ) { }\n</code></pre>\n"
},
{
"answer_id": 354978,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 0,
"selected": false,
"text": "<p>I think the value would only be present if you add the get-param to the url when trying to preview it ( or specifically set a value for the query-var using <code>$query->set()</code> )</p>\n\n<p>Try adding <code>?xyz=hello-world</code> to the end of the url you're testing on & you should see <code>hello-world</code> in the dump. </p>\n\n<p>It will also depend on where you dump... maybe try this:</p>\n\n<pre><code>add_filter('query_vars', function ($vars) {\n $vars[] = 'xyz';\n return $vars;\n});\n</code></pre>\n\n<p>then visit: <code>yoursite.com/?xyz=hello-world</code></p>\n\n<pre><code>function trythis( $wp_query ) {\n if ( $wp_query->is_main_query() && ! is_admin() ) {\n var_dump( $wp_query ); \n exit;\n }\n}\nadd_action( 'pre_get_posts', 'trythis' );\n</code></pre>\n\n<p>... & you should see <code>'xyz'=>'hello-world'</code> in the dump. I don't think query vars are added to wp-query unless they need to be, that'd add unnecessary bloat.</p>\n"
}
] |
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 <code>false</code> to <code>'has_archive' => true,</code>.</p>\n\n<pre><code>function custom_post_type() {\n\n $labels = array( ... );\n $args = array(\n\n // you have to set it to False.\n 'has_archive' => false,\n\n );\n register_post_type( 'post_type', $args );\n\n}\nadd_action( 'init', 'custom_post_type', 0 );\n</code></pre>\n"
},
{
"answer_id": 298673,
"author": "H. Rensenbrink",
"author_id": 122754,
"author_profile": "https://wordpress.stackexchange.com/users/122754",
"pm_score": 2,
"selected": false,
"text": "<p>This question has been asked a long time ago, but the answer is kind of simple:</p>\n\n<ul>\n<li>Go to SEO --> Search Appearance.</li>\n<li>Select tab Contenttypes.</li>\n<li>Scroll down, here you can display or hide custom post types and archives from the sitemap.xml file.</li>\n</ul>\n\n<p>Hope that helps for someone.</p>\n"
},
{
"answer_id": 402508,
"author": "Brandon",
"author_id": 203783,
"author_profile": "https://wordpress.stackexchange.com/users/203783",
"pm_score": 1,
"selected": false,
"text": "<p>If you need a filter solution:</p>\n<pre><code>add_filter( 'wpseo_sitemap_exclude_post_type', 'your_prefix_exclude_cpt_from_sitemap', 10, 2 );\n\nfunction your_prefix_exclude_cpt_from_sitemap( $value, $post_type ) {\n $post_types_to_exclude = [\n 'post_type_one',\n 'post_type_two'\n ];\n \n if ( in_array($post_type, $post_types_to_exclude) ) {\n return true;\n }\n}\n</code></pre>\n<p>You can use the "post_types_to_exclude" array to define multiple post types you want to exclude from the sitemap.</p>\n"
}
] |
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_post</code></a> 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:</p>\n\n<pre><code><?php\nadd_action( 'save_post', function( $post_ID, $post, $update ) {\n if ( 'trash' === $post->post_status ) {\n return;\n }\n\n /** do your stuff **/\n}, 10, 3 );\n?>\n</code></pre>\n"
},
{
"answer_id": 403320,
"author": "atwellpub",
"author_id": 2798,
"author_profile": "https://wordpress.stackexchange.com/users/2798",
"pm_score": 1,
"selected": false,
"text": "<p>The following helps for skipping the restore option as well as the trash option:</p>\n<pre><code><?php\nadd_action( 'save_post_POSTTYPEHERE', function( $post_ID, $post, $update ) {\n \n /* do not save meta on trash/untrash event */\n if(\n isset($_REQUEST['action']) &&\n ( $_REQUEST['action'] == 'trash' || $_REQUEST['action'] == 'untrash')\n ){\n return;\n }\n\n /** do your stuff **/\n \n}, 10, 3 );\n?>\n</code></pre>\n"
}
] |
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, you need to hook through product excerpt.</p>\n\n<pre><code>add_filter('get_the_excerpt', 'custom_excerpt');\n\nfunction exc($custom_excerpt) {\n global $post;\n\n if($post->post_type == 'product'){\n $custom_add = __('This product is unavailable for some countries, please, read our terms & conditions to know more about this.', 'folkstone');\n\n return $excerpt . $custom_add;\n }else{\n return $excerpt;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 243895,
"author": "yaveii93",
"author_id": 60721,
"author_profile": "https://wordpress.stackexchange.com/users/60721",
"pm_score": 0,
"selected": false,
"text": "<p>Benoti. </p>\n\n<p>I was able to solve the problem that I had with this code:</p>\n\n<pre><code>add_action('woocommerce_after_shop_loop_item_title', 'lk_woocommerce_product_excerpt', 35, 2);\nif (!function_exists('lk_woocommerce_product_excerpt')) {\n function lk_woocommerce_product_excerpt()\n {\n $content_length = 10;\n global $post;\n $content = $post->brief_description;\n $wordarray = explode(' ', $content, $content_length + 1);\n if (count($wordarray) > $content_length) :\n array_pop($wordarray);\n array_push($wordarray, '...');\n $content = implode(' ', $wordarray);\n $content = force_balance_tags($content);\n endif;\n echo \"<span class='excerpt'><p>$content</p></span>\";\n }\n}\n</code></pre>\n\n<p>Thanks for taking your time and try helping me. </p>\n"
}
] |
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 resolves the problem. If it does, re-enable each one until you come across the error again and hopefully you'll find the culprit.</p>\n\n<p>Of course, this won't solve your issue entirely but if it does work then it will help too narrow the cause.</p>\n"
},
{
"answer_id": 243546,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>Generate your <code>.htaccess</code> again. For that go to <code>Settings >> Permalinks</code> then hit <code>Save Changes</code> button. It will re-generate your <code>.htaccess</code> file. If it's no resolved, you can try the <code>FTP</code> described in comment by @Benoti. If that's also not worked please try <a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-fix-the-403-forbidden-error-in-wordpress/\" rel=\"nofollow\">this blog</a>.</p>\n"
}
] |
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 user IDs and subsites IDs first, then it's looping over every sites and users to assign all the users to every subsite. Here is the updated code-</p>\n\n<pre><code>add_action('wp','the_dramatist_add_current_user_to_site');\nfunction the_dramatist_add_current_user_to_site() {\n global $wpdb;\n $all_users = $wpdb->get_col( 'SELECT ID FROM $wpdb->users' );\n $subsites = get_sites();\n foreach( $subsites as $subsite ) {\n $subsite_id = get_object_vars($subsite)['blog_id'];\n foreach ( $all_users as $current_user) {\n $blog_id = get_current_blog_id();\n $user_id = ($current_user->ID);\n\n switch_to_blog($subsite_id);\n $get_role = ($current_user->caps);\n $add_role = key($get_role);\n restore_current_blog();\n\n if (!is_user_member_of_blog( $user_id, $blog_id ) ) {\n add_user_to_blog( $blog_id, $user_id, $add_role );\n }\n }\n }\n}\n</code></pre>\n\n<p>Hope that thing helps.</p>\n"
},
{
"answer_id": 243787,
"author": "Morgan",
"author_id": 88515,
"author_profile": "https://wordpress.stackexchange.com/users/88515",
"pm_score": 1,
"selected": true,
"text": "<p>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.</p>\n\n<p>It can be set up to either add the current user or all users from a site (I chose the main network site, <code>blog_id=1</code>) to the subsite when they visit the page.</p>\n\n<p>Here is how to do both, choose one and add to <code>functions.php</code>:</p>\n\n<p><strong>Add only the user to each subsite</strong></p>\n\n<pre><code>function add_current_user_to_site() {\n if(!is_user_logged_in()) {\n return false;\n }\n\n $current_user = wp_get_current_user();\n $blog_id = get_current_blog_id();\n $user_id = ($current_user->ID);\n\n switch_to_blog(1);\n $get_role = ($current_user->caps);\n $add_role = key($get_role);\n restore_current_blog();\n\n if (!is_user_member_of_blog( $user_id, $blog_id ) ) {\n add_user_to_blog( $blog_id, $user_id, $add_role );\n }\n}\nadd_action('wp','add_current_user_to_site');\n</code></pre>\n\n<hr>\n\n<p><strong>Add all users to each subsite</strong></p>\n\n<pre><code>function add_all_users_to_site() {\n if(!is_user_logged_in()) {\n return false;\n }\n\n $users = get_users('blog_id=1');\n $sites = get_sites();\n\n foreach ($sites as $site) {\n foreach ($users as $user) {\n $blog_id = get_current_blog_id();\n $user_id = ($user->ID);\n\n switch_to_blog($site->id);\n $get_role = ($user->caps);\n $add_role = key($get_role);\n restore_current_blog();\n\n if (!is_user_member_of_blog( $user_id, $blog_id ) ) {\n add_user_to_blog( $blog_id, $user_id, $add_role );\n }\n }\n }\n}\nadd_action('wp','add_all_users_to_site');\n</code></pre>\n"
}
] |
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 <code>update_post_meta( $post_id, 'field_name', $update_var )</code> or it does not executes, cause the indentation. So I think the below code will do your job-</p>\n\n<pre><code>function stuff_save( $post_id ) {\n\n $post_type = get_post_type($post_id);\n\n // If this is just a revision, do nothing.\n if ( wp_is_post_revision( $post_id )|| \"animations\" != $post_type ) {\n return; \n }\n\n /**code to generate data points**/\n $datapoint = get_post_meta($post_id,custom_field,1);\n $update_var= string_from_API_Call;\n\n /**uses $datapoint to do a thing; I'm using this result elsewhere, can echo it, and it's successful.**/ \n $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.\n\n}\n\nadd_action( 'save_post', 'stuff_save' );\n</code></pre>\n"
},
{
"answer_id": 243560,
"author": "BlueDreaming",
"author_id": 57332,
"author_profile": "https://wordpress.stackexchange.com/users/57332",
"pm_score": 2,
"selected": true,
"text": "<p>I solved my own problem. </p>\n\n<p>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. </p>\n\n<p>What this means essentially is that I'm overwriting my values with blank formdata. </p>\n\n<p>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. </p>\n\n<pre><code>$hat = update_post_meta( $post_id, 'field_name', $update_var );\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>/**document this well or you'll drive someone insane in the future.**/ \n\n\n$_POST['field_name'] = $update_var;\n</code></pre>\n\n<p>Thanks everyone for your thoughts and attempts to help. You no doubt inspired me to think about it. </p>\n"
}
] |
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</code> opening tags at the top which would certainly cause an error. But I think that's leftover from your copy and paste. </p>\n\n<ul>\n<li>Look at your php server log which will tell you what file and line number the error is occurring.</li>\n<li>Put the following in your <code>wp-config.php</code> file which will print all errors in your browser. Then you won't have to access the php log directly.</li>\n</ul>\n\n<p>Code to add:</p>\n\n<pre><code>define( 'WP_DEBUG', true );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Debugging_in_WordPress#WP_DEBUG\" rel=\"nofollow\">WordPress Debugging Guide</a></p>\n"
},
{
"answer_id": 243567,
"author": "amit singh",
"author_id": 105452,
"author_profile": "https://wordpress.stackexchange.com/users/105452",
"pm_score": 0,
"selected": false,
"text": "<p>Why are you opening so many php tags without any reason?\nHere is the reviewed code, please check if it works:</p>\n\n<pre><code><?php\nadd_action( 'wp_ajax_posts_by_brand_action', 'posts_by_brand_action_callback' );\n\nfunction posts_by_brand_action_callback() {\n global $wpdb; // this is how you get access to the database\n\n $brand = $_POST['brand'];\n\n echo $whatever;\n\n // ----- START OF BRAND FILTER CODE\n\n\n // args\n $args = array(\n //'numberposts' => -1,\n //'post_type' => 'event',\n 'meta_key' => 'brand',\n 'meta_value' => $brand\n );\n\n\n // query\n $the_query = new WP_Query( $args );\n\n if($the_query->have_posts() ):\n?>\n <ul>\n <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\">\n <?php the_title(); ?>\n </a>\n </li>\n <?php endwhile; ?>\n </ul>\n <?php\n endif;\n\n wp_reset_query(); // Restore global post data stomped by the_post().\n\n // ------ END OF BRAND FILTER CODE\n\n wp_die(); // this is required to terminate immediately and return a proper response\n}\n?>\n</code></pre>\n"
}
] |
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 recommendation would be to wrap all your text strings in <code>__()</code> or <code>_e()</code> so they can easily be translated. This is a nice selling point on marketplace sites like ThemeForest since not everyone wants to use English.</p>\n\n<pre><code>$output .= '<label for=\"' . esc_attr( $tid ) . '\">' . __( 'Title:', 'your-text-domain' ) . '</label>';\n</code></pre>\n\n<p>Read more about <a href=\"https://codex.wordpress.org/I18n_for_WordPress_Developers#Text_Domains\" rel=\"nofollow\">I18n on the WordPress Codex</a>.</p>\n"
},
{
"answer_id": 249013,
"author": "guillaume.molter",
"author_id": 76144,
"author_profile": "https://wordpress.stackexchange.com/users/76144",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to do it the \"WordPress way\", you would not store your HTML in a temporary variable, you would output directly.</p>\n\n<pre><code>?> \n<p>\n <label for=\"<?php esc_attr_e( $this->get_field_id( 'title' ) ); ?>\"> <?php _e('Title:', 'tex-domain'); ?></label>\n <input type=\"text\" class=\"widefat\" id=\"<?php esc_attr_e( $this->get_field_id( 'title' ) ); ?>\" value=\"<?php esc_attr_e( $title ); ?>\" />\n</p>\n<?php \n</code></pre>\n\n<p>P.S: You would also <a href=\"https://codex.wordpress.org/I18n_for_WordPress_Developers\" rel=\"nofollow noreferrer\">internationalize</a> your text strings.</p>\n"
},
{
"answer_id": 296172,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 1,
"selected": false,
"text": "<p><strong>1. Escaping</strong></p>\n\n<ul>\n<li><p>Escaping Attribute <code><label for=\"<?php esc_attr( $tid ); ?>\"></code></p></li>\n<li><p>Escaping HTML <code><label ..><?php esc_html( 'Text' ); ?></label></code></p></li>\n</ul>\n\n<hr>\n\n<p><strong>2. Translation and Escape</strong></p>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n<li><code>textdomain</code> should be your own unique theme/plugin slug.</li>\n<li>The translated string should contain a static value. If you have a dynamic value then no need to make it translation ready.</li>\n</ul>\n\n<p><br/>\n1. Escape and translate Attribute: <code><label for=\"<?php esc_attr( $tid ); ?>\"></code></p>\n\n<p>No need to make it translation ready. If you have a static string with <code>$tid</code> then you need to make it transition ready eg.</p>\n\n<p><strong>Invalid:</strong></p>\n\n<pre><code><label for=\"<?php esc_attr__( $tid, 'textdomain' ) ); ?>\">\n<label for=\"<?php printf( esc_attr__( '%s', 'textdomain' ), $tid ); ?>\">\n</code></pre>\n\n<p><strong>Valid:</strong></p>\n\n<pre><code><label for=\"<?php printf( esc_attr__( '%s static text', 'textdomain' ), $tid ); ?>\">\n</code></pre>\n\n<ol start=\"2\">\n<li>Escape and translate HTML: <code><label ..><?php esc_html__( 'Text', 'textdomain' ); ?></label></code></li>\n</ol>\n"
},
{
"answer_id": 314939,
"author": "Jory Hogeveen",
"author_id": 99325,
"author_profile": "https://wordpress.stackexchange.com/users/99325",
"pm_score": 3,
"selected": false,
"text": "<p>You are looking for <code>wp_kses()</code>. <a href=\"https://developer.wordpress.org/reference/functions/wp_kses/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_kses/</a></p>\n<p>There are more helper functions like <code>wp_kses_post()</code> and <code>wp_kses_data()</code></p>\n"
},
{
"answer_id": 393572,
"author": "ApsaraAruna",
"author_id": 105670,
"author_profile": "https://wordpress.stackexchange.com/users/105670",
"pm_score": 1,
"selected": false,
"text": "<p>try with this method. this is work for me. echo escape with html.</p>\n<pre><code>$output = '<p>';\n$output .= '<label for="' . esc_attr( $this->get_field_id( 'title' ) ) . '">Title:</label>';\n$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 ) . '"';\n$output .= '</p>'; \n\n$allowed_html = array(\n 'input' => array(\n 'type' => array(),\n 'id' => array(),\n 'name' => array(),\n 'value' => array(),\n ),\n);\n\necho wp_kses($output ,$allowed_html );\n</code></pre>\n"
}
] |
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 recommendation would be to wrap all your text strings in <code>__()</code> or <code>_e()</code> so they can easily be translated. This is a nice selling point on marketplace sites like ThemeForest since not everyone wants to use English.</p>\n\n<pre><code>$output .= '<label for=\"' . esc_attr( $tid ) . '\">' . __( 'Title:', 'your-text-domain' ) . '</label>';\n</code></pre>\n\n<p>Read more about <a href=\"https://codex.wordpress.org/I18n_for_WordPress_Developers#Text_Domains\" rel=\"nofollow\">I18n on the WordPress Codex</a>.</p>\n"
},
{
"answer_id": 249013,
"author": "guillaume.molter",
"author_id": 76144,
"author_profile": "https://wordpress.stackexchange.com/users/76144",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to do it the \"WordPress way\", you would not store your HTML in a temporary variable, you would output directly.</p>\n\n<pre><code>?> \n<p>\n <label for=\"<?php esc_attr_e( $this->get_field_id( 'title' ) ); ?>\"> <?php _e('Title:', 'tex-domain'); ?></label>\n <input type=\"text\" class=\"widefat\" id=\"<?php esc_attr_e( $this->get_field_id( 'title' ) ); ?>\" value=\"<?php esc_attr_e( $title ); ?>\" />\n</p>\n<?php \n</code></pre>\n\n<p>P.S: You would also <a href=\"https://codex.wordpress.org/I18n_for_WordPress_Developers\" rel=\"nofollow noreferrer\">internationalize</a> your text strings.</p>\n"
},
{
"answer_id": 296172,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 1,
"selected": false,
"text": "<p><strong>1. Escaping</strong></p>\n\n<ul>\n<li><p>Escaping Attribute <code><label for=\"<?php esc_attr( $tid ); ?>\"></code></p></li>\n<li><p>Escaping HTML <code><label ..><?php esc_html( 'Text' ); ?></label></code></p></li>\n</ul>\n\n<hr>\n\n<p><strong>2. Translation and Escape</strong></p>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n<li><code>textdomain</code> should be your own unique theme/plugin slug.</li>\n<li>The translated string should contain a static value. If you have a dynamic value then no need to make it translation ready.</li>\n</ul>\n\n<p><br/>\n1. Escape and translate Attribute: <code><label for=\"<?php esc_attr( $tid ); ?>\"></code></p>\n\n<p>No need to make it translation ready. If you have a static string with <code>$tid</code> then you need to make it transition ready eg.</p>\n\n<p><strong>Invalid:</strong></p>\n\n<pre><code><label for=\"<?php esc_attr__( $tid, 'textdomain' ) ); ?>\">\n<label for=\"<?php printf( esc_attr__( '%s', 'textdomain' ), $tid ); ?>\">\n</code></pre>\n\n<p><strong>Valid:</strong></p>\n\n<pre><code><label for=\"<?php printf( esc_attr__( '%s static text', 'textdomain' ), $tid ); ?>\">\n</code></pre>\n\n<ol start=\"2\">\n<li>Escape and translate HTML: <code><label ..><?php esc_html__( 'Text', 'textdomain' ); ?></label></code></li>\n</ol>\n"
},
{
"answer_id": 314939,
"author": "Jory Hogeveen",
"author_id": 99325,
"author_profile": "https://wordpress.stackexchange.com/users/99325",
"pm_score": 3,
"selected": false,
"text": "<p>You are looking for <code>wp_kses()</code>. <a href=\"https://developer.wordpress.org/reference/functions/wp_kses/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_kses/</a></p>\n<p>There are more helper functions like <code>wp_kses_post()</code> and <code>wp_kses_data()</code></p>\n"
},
{
"answer_id": 393572,
"author": "ApsaraAruna",
"author_id": 105670,
"author_profile": "https://wordpress.stackexchange.com/users/105670",
"pm_score": 1,
"selected": false,
"text": "<p>try with this method. this is work for me. echo escape with html.</p>\n<pre><code>$output = '<p>';\n$output .= '<label for="' . esc_attr( $this->get_field_id( 'title' ) ) . '">Title:</label>';\n$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 ) . '"';\n$output .= '</p>'; \n\n$allowed_html = array(\n 'input' => array(\n 'type' => array(),\n 'id' => array(),\n 'name' => array(),\n 'value' => array(),\n ),\n);\n\necho wp_kses($output ,$allowed_html );\n</code></pre>\n"
}
] |
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 recommendation would be to wrap all your text strings in <code>__()</code> or <code>_e()</code> so they can easily be translated. This is a nice selling point on marketplace sites like ThemeForest since not everyone wants to use English.</p>\n\n<pre><code>$output .= '<label for=\"' . esc_attr( $tid ) . '\">' . __( 'Title:', 'your-text-domain' ) . '</label>';\n</code></pre>\n\n<p>Read more about <a href=\"https://codex.wordpress.org/I18n_for_WordPress_Developers#Text_Domains\" rel=\"nofollow\">I18n on the WordPress Codex</a>.</p>\n"
},
{
"answer_id": 249013,
"author": "guillaume.molter",
"author_id": 76144,
"author_profile": "https://wordpress.stackexchange.com/users/76144",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to do it the \"WordPress way\", you would not store your HTML in a temporary variable, you would output directly.</p>\n\n<pre><code>?> \n<p>\n <label for=\"<?php esc_attr_e( $this->get_field_id( 'title' ) ); ?>\"> <?php _e('Title:', 'tex-domain'); ?></label>\n <input type=\"text\" class=\"widefat\" id=\"<?php esc_attr_e( $this->get_field_id( 'title' ) ); ?>\" value=\"<?php esc_attr_e( $title ); ?>\" />\n</p>\n<?php \n</code></pre>\n\n<p>P.S: You would also <a href=\"https://codex.wordpress.org/I18n_for_WordPress_Developers\" rel=\"nofollow noreferrer\">internationalize</a> your text strings.</p>\n"
},
{
"answer_id": 296172,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 1,
"selected": false,
"text": "<p><strong>1. Escaping</strong></p>\n\n<ul>\n<li><p>Escaping Attribute <code><label for=\"<?php esc_attr( $tid ); ?>\"></code></p></li>\n<li><p>Escaping HTML <code><label ..><?php esc_html( 'Text' ); ?></label></code></p></li>\n</ul>\n\n<hr>\n\n<p><strong>2. Translation and Escape</strong></p>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n<li><code>textdomain</code> should be your own unique theme/plugin slug.</li>\n<li>The translated string should contain a static value. If you have a dynamic value then no need to make it translation ready.</li>\n</ul>\n\n<p><br/>\n1. Escape and translate Attribute: <code><label for=\"<?php esc_attr( $tid ); ?>\"></code></p>\n\n<p>No need to make it translation ready. If you have a static string with <code>$tid</code> then you need to make it transition ready eg.</p>\n\n<p><strong>Invalid:</strong></p>\n\n<pre><code><label for=\"<?php esc_attr__( $tid, 'textdomain' ) ); ?>\">\n<label for=\"<?php printf( esc_attr__( '%s', 'textdomain' ), $tid ); ?>\">\n</code></pre>\n\n<p><strong>Valid:</strong></p>\n\n<pre><code><label for=\"<?php printf( esc_attr__( '%s static text', 'textdomain' ), $tid ); ?>\">\n</code></pre>\n\n<ol start=\"2\">\n<li>Escape and translate HTML: <code><label ..><?php esc_html__( 'Text', 'textdomain' ); ?></label></code></li>\n</ol>\n"
},
{
"answer_id": 314939,
"author": "Jory Hogeveen",
"author_id": 99325,
"author_profile": "https://wordpress.stackexchange.com/users/99325",
"pm_score": 3,
"selected": false,
"text": "<p>You are looking for <code>wp_kses()</code>. <a href=\"https://developer.wordpress.org/reference/functions/wp_kses/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_kses/</a></p>\n<p>There are more helper functions like <code>wp_kses_post()</code> and <code>wp_kses_data()</code></p>\n"
},
{
"answer_id": 393572,
"author": "ApsaraAruna",
"author_id": 105670,
"author_profile": "https://wordpress.stackexchange.com/users/105670",
"pm_score": 1,
"selected": false,
"text": "<p>try with this method. this is work for me. echo escape with html.</p>\n<pre><code>$output = '<p>';\n$output .= '<label for="' . esc_attr( $this->get_field_id( 'title' ) ) . '">Title:</label>';\n$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 ) . '"';\n$output .= '</p>'; \n\n$allowed_html = array(\n 'input' => array(\n 'type' => array(),\n 'id' => array(),\n 'name' => array(),\n 'value' => array(),\n ),\n);\n\necho wp_kses($output ,$allowed_html );\n</code></pre>\n"
}
] |
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']=='trash'){\n add_action( 'admin_notices', 'show_post_order_info' );\n}\n</code></pre>\n"
},
{
"answer_id": 243619,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<h2>Checking the bulk counts</h2>\n\n<p>We can check the <em>bulk counts</em>, to see if any post was <em>deleted</em>:</p>\n\n<pre><code>add_filter( 'bulk_post_updated_messages', function( $bulk_messages, $bulk_counts )\n{\n // Check the bulk counts for 'deleted' and add notice if it's gt 0\n if( isset( $bulk_counts['deleted'] ) && $bulk_counts['deleted'] > 0 )\n add_filter( 'admin_notices', 'wpse_243594_notice' );\n\n return $bulk_messages;\n}, 10, 2 );\n</code></pre>\n\n<p>where we define the callback with our custom notice as:</p>\n\n<pre><code>function wpse_243594_notice()\n{\n printf( \n '<div class=\"notice notice-info is-dismissible\">%s</div>',\n esc_html__( 'Hello World!', 'domain' )\n );\n}\n</code></pre>\n\n<p>The bulk counts contains further info for <em>updated</em>, <em>locked</em>, <em>trashed</em> and <em>untrashed</em>.</p>\n\n<h2>Output example</h2>\n\n<p><a href=\"https://i.stack.imgur.com/xlJWm.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xlJWm.jpg\" alt=\"custom notice on post delete\"></a></p>\n\n<p>Hope you can adjust this further to your needs!</p>\n"
}
] |
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 <code>$_REQUEST['menu-item-custom-category'][$menu_item_db_id]</code> became to an <code>array()</code>. for checking this must use php <code>is_array()</code> function.</p>\n\n<p>Then when you deselect the options that means the <code>$_REQUEST['menu-item-custom-category'][$menu_item_db_id])</code> not stay as an array. Then in this case the <code>delete_post_meta()</code> work and delete all options in your specified <code>_menu_item_content_multiple</code> meta key</p>\n\n<p>means you must use <code>if()</code> and <code>else{}</code> php conditional statement as below</p>\n\n<pre><code><?php\n if(is_array($_REQUEST['menu-item-content-multiple'][$menu_item_db_id])) {\n $values = $_REQUEST['menu-item-content-multiple'][$menu_item_db_id];\n foreach($values as $value) {\n add_post_meta($menu_item_db_id, '_menu_item_content_multiple', $value);\n }\n } else {\n delete_post_meta($menu_item_db_id, '_menu_item_content_multiple');\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 243673,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>I think it is just a matter of logic. If you don't select any value, <code>$_REQUEST['menu-item-custom-category'][$menu_item_db_id]</code> is empty. So, the next line <code>delete_post_meta()</code> is never triggered in your code. Just think in the logic you need to know when to delete previous meta value.</p>\n\n<p>For example:</p>\n\n<pre><code>if( !empty( $_REQUEST['menu-item-custom-category'][$menu_item_db_id] ) ) {\n\n // Delete all previous values from database and save\n // only the selected values in the current request\n delete_post_meta( $menu_item_db_id, '_menu_item_custom_category' );\n\n $values = $_REQUEST['menu-item-custom-category'][$menu_item_db_id];\n\n if( is_array( $values ) ) {\n // We have several values\n // Sanitize values first (needed if you have not registered a sanitization callback with register_meta())\n $values = array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) );\n foreach( $values as $value ) {\n add_post_meta( $menu_item_db_id, '_menu_item_custom_category', $value );\n }\n } else {\n // We have single value\n add_post_meta( $menu_item_db_id, '_menu_item_custom_category', sanitize_text_field( $values ) );\n }\n\n} else {\n\n // All values unselected, delete all of them from post meta\n delete_post_meta($menu_item_db_id, '_menu_item_custom_category');\n\n}\n</code></pre>\n\n<p>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 <a href=\"https://wordpress.stackexchange.com/a/107556/37428\">this answer</a>):</p>\n\n<pre><code>if ( empty( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) ) {\n\n // no values selected, delete all post meta for our key\n delete_post_meta( $menu_item_db_id, '_menu_item_content_multiple' );\n\n} else {\n\n $old_values = get_post_meta( $menu_item_db_id, '_menu_item_custom_category' );\n $new_values = $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] \n $values_to_skip = array();\n\n if( !empty( $old_values ) ) {\n\n foreach( $old_values as $old_value ) {\n\n if ( ! in_array( $old_value, $new_values ) ) {\n\n // this value was in meta, but now it is not selected,\n // so it has to be deletec\n delete_post_meta( $menu_item_db_id, '_menu_item_custom_category', $old_value );\n\n } else {\n\n // This value was in meta and it is selected again,\n // So, we don't need to save it again\n $values_to_skip[] = $old_value;\n\n }\n }\n }\n\n // Get the values that are not already in database\n // And store them\n $values_to_save = array_diff( $new_values, $values_to_skip );\n\n if ( ! empty( $values_to_save ) ) {\n\n foreach ( $values_to_save as $value ) {\n\n add_post_meta( $menu_item_db_id, '_menu_item_content_multiple', $value );\n\n }\n }\n}\n</code></pre>\n"
}
] |
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 <code>$_REQUEST['menu-item-custom-category'][$menu_item_db_id]</code> became to an <code>array()</code>. for checking this must use php <code>is_array()</code> function.</p>\n\n<p>Then when you deselect the options that means the <code>$_REQUEST['menu-item-custom-category'][$menu_item_db_id])</code> not stay as an array. Then in this case the <code>delete_post_meta()</code> work and delete all options in your specified <code>_menu_item_content_multiple</code> meta key</p>\n\n<p>means you must use <code>if()</code> and <code>else{}</code> php conditional statement as below</p>\n\n<pre><code><?php\n if(is_array($_REQUEST['menu-item-content-multiple'][$menu_item_db_id])) {\n $values = $_REQUEST['menu-item-content-multiple'][$menu_item_db_id];\n foreach($values as $value) {\n add_post_meta($menu_item_db_id, '_menu_item_content_multiple', $value);\n }\n } else {\n delete_post_meta($menu_item_db_id, '_menu_item_content_multiple');\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 243673,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>I think it is just a matter of logic. If you don't select any value, <code>$_REQUEST['menu-item-custom-category'][$menu_item_db_id]</code> is empty. So, the next line <code>delete_post_meta()</code> is never triggered in your code. Just think in the logic you need to know when to delete previous meta value.</p>\n\n<p>For example:</p>\n\n<pre><code>if( !empty( $_REQUEST['menu-item-custom-category'][$menu_item_db_id] ) ) {\n\n // Delete all previous values from database and save\n // only the selected values in the current request\n delete_post_meta( $menu_item_db_id, '_menu_item_custom_category' );\n\n $values = $_REQUEST['menu-item-custom-category'][$menu_item_db_id];\n\n if( is_array( $values ) ) {\n // We have several values\n // Sanitize values first (needed if you have not registered a sanitization callback with register_meta())\n $values = array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) );\n foreach( $values as $value ) {\n add_post_meta( $menu_item_db_id, '_menu_item_custom_category', $value );\n }\n } else {\n // We have single value\n add_post_meta( $menu_item_db_id, '_menu_item_custom_category', sanitize_text_field( $values ) );\n }\n\n} else {\n\n // All values unselected, delete all of them from post meta\n delete_post_meta($menu_item_db_id, '_menu_item_custom_category');\n\n}\n</code></pre>\n\n<p>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 <a href=\"https://wordpress.stackexchange.com/a/107556/37428\">this answer</a>):</p>\n\n<pre><code>if ( empty( $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] ) ) {\n\n // no values selected, delete all post meta for our key\n delete_post_meta( $menu_item_db_id, '_menu_item_content_multiple' );\n\n} else {\n\n $old_values = get_post_meta( $menu_item_db_id, '_menu_item_custom_category' );\n $new_values = $_REQUEST['menu-item-content-multiple'][$menu_item_db_id] \n $values_to_skip = array();\n\n if( !empty( $old_values ) ) {\n\n foreach( $old_values as $old_value ) {\n\n if ( ! in_array( $old_value, $new_values ) ) {\n\n // this value was in meta, but now it is not selected,\n // so it has to be deletec\n delete_post_meta( $menu_item_db_id, '_menu_item_custom_category', $old_value );\n\n } else {\n\n // This value was in meta and it is selected again,\n // So, we don't need to save it again\n $values_to_skip[] = $old_value;\n\n }\n }\n }\n\n // Get the values that are not already in database\n // And store them\n $values_to_save = array_diff( $new_values, $values_to_skip );\n\n if ( ! empty( $values_to_save ) ) {\n\n foreach ( $values_to_save as $value ) {\n\n add_post_meta( $menu_item_db_id, '_menu_item_content_multiple', $value );\n\n }\n }\n}\n</code></pre>\n"
}
] |
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 at the end of it) and <code>wp_footer()</code> somewhere in your footer section. Those are <strong>mandatory</strong> 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.</p>\n\n<p>If you do a \"plain\" HTML page, you have to manually insert the various CSS and JS into the HTML. </p>\n"
},
{
"answer_id": 243820,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Although Marks answer deserves some respect, at the moment I am writing this he didn't mention probably the most important functions you need to have.</p>\n\n<pre><code>add_action( 'wp_head', ...\nadd_action( 'wp_footer', ...\n</code></pre>\n\n<p>I would take another approach in your case. Let's forget your theme for a second. I would start modifying some simple WordPress theme. </p>\n\n<p>This may be the <code>_s</code> theme. \"S\" may stand for the <code>Starter</code>, or <code>Start Up</code>.</p>\n\n<p>It looks so simple, but in fact, underneath you will have a Lamborghini engine. You will find in there all the good practices already implemented and <code>wp_head</code> and <code>wp_footer</code> actions you are missing.</p>\n\n<p>Try to remove them and you will experience the same problem you had with your them. </p>\n\n<p>Your further task may be to add some cool CSS to the theme and your theme may be fantastic after that.</p>\n\n<p>More, you will be able to experiment with the Oenology theme.\n<a href=\"https://wordpress.org/themes/oenology/\" rel=\"nofollow\">https://wordpress.org/themes/oenology/</a></p>\n\n<p>This is a great theme that looks not so great (to be honest), but the code in there is a world class. Like a Rolls Royce or Bugatti.</p>\n\n<p>I guess you are a beginner and I gave you +1 for your effort digging into the WordPress - platform of the future.</p>\n\n<p>I congratulate you on your determination to work in WordPress and I wish you all the luck.</p>\n"
}
] |
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 at the end of it) and <code>wp_footer()</code> somewhere in your footer section. Those are <strong>mandatory</strong> 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.</p>\n\n<p>If you do a \"plain\" HTML page, you have to manually insert the various CSS and JS into the HTML. </p>\n"
},
{
"answer_id": 243820,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Although Marks answer deserves some respect, at the moment I am writing this he didn't mention probably the most important functions you need to have.</p>\n\n<pre><code>add_action( 'wp_head', ...\nadd_action( 'wp_footer', ...\n</code></pre>\n\n<p>I would take another approach in your case. Let's forget your theme for a second. I would start modifying some simple WordPress theme. </p>\n\n<p>This may be the <code>_s</code> theme. \"S\" may stand for the <code>Starter</code>, or <code>Start Up</code>.</p>\n\n<p>It looks so simple, but in fact, underneath you will have a Lamborghini engine. You will find in there all the good practices already implemented and <code>wp_head</code> and <code>wp_footer</code> actions you are missing.</p>\n\n<p>Try to remove them and you will experience the same problem you had with your them. </p>\n\n<p>Your further task may be to add some cool CSS to the theme and your theme may be fantastic after that.</p>\n\n<p>More, you will be able to experiment with the Oenology theme.\n<a href=\"https://wordpress.org/themes/oenology/\" rel=\"nofollow\">https://wordpress.org/themes/oenology/</a></p>\n\n<p>This is a great theme that looks not so great (to be honest), but the code in there is a world class. Like a Rolls Royce or Bugatti.</p>\n\n<p>I guess you are a beginner and I gave you +1 for your effort digging into the WordPress - platform of the future.</p>\n\n<p>I congratulate you on your determination to work in WordPress and I wish you all the luck.</p>\n"
}
] |
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->prepare</code>.</p>\n\n<p>I've also included a more efficient Haversine formula (<a href=\"https://developers.google.com/maps/articles/phpsqlsearch_v3#findnearsql\" rel=\"nofollow noreferrer\">source</a>) to calculate the radius.</p>\n\n<p>If you use kilometers, then change the <code>$earth_radius</code> to 6371.</p>\n\n<p>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.</p>\n\n<pre><code>function get_nearby_locations( $lat, $lng, $distance ) {\n global $wpdb;\n\n // Radius of the earth 3959 miles or 6371 kilometers.\n $earth_radius = 3959;\n\n $sql = $wpdb->prepare( \"\n SELECT DISTINCT\n p.ID,\n p.post_title,\n map_lat.meta_value as locLat,\n map_lng.meta_value as locLong,\n ( %d * acos(\n cos( radians( %s ) )\n * cos( radians( map_lat.meta_value ) )\n * cos( radians( map_lng.meta_value ) - radians( %s ) )\n + sin( radians( %s ) )\n * sin( radians( map_lat.meta_value ) )\n ) )\n AS distance\n FROM $wpdb->posts p\n INNER JOIN $wpdb->postmeta map_lat ON p.ID = map_lat.post_id\n INNER JOIN $wpdb->postmeta map_lng ON p.ID = map_lng.post_id\n WHERE 1 = 1\n AND p.post_type = 'beaches'\n AND p.post_status = 'publish'\n AND map_lat.meta_key = 'map_lat'\n AND map_lng.meta_key = 'map_lng'\n HAVING distance < %s\n ORDER BY distance ASC\",\n $earth_radius,\n $lat,\n $lng,\n $lat,\n $distance\n );\n\n // Uncomment and paste into phpMyAdmin to debug.\n // echo $sql;\n\n $nearbyLocations = $wpdb->get_results( $sql );\n\n if ( $nearbyLocations ) {\n return $nearbyLocations;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 243757,
"author": "Rafal",
"author_id": 105189,
"author_profile": "https://wordpress.stackexchange.com/users/105189",
"pm_score": -1,
"selected": false,
"text": "<p>I managed to make it work:</p>\n\n<pre><code>function get_nearby_locations( $lat, $long, $distance ) {\n global $wpdb;\n\n // Radius of the earth 3959 miles or 6371 kilometers.\n $earth_radius = 3959;\n\n $sql = $wpdb->prepare( \"\n SELECT DISTINCT\n map_lat.post_id,\n p.post_title,\n map_lat.meta_value as locLat,\n map_lng.meta_value as locLong,\n\n (\n 6371 * ACOS(\n COS(RADIANS( %s )) * COS(RADIANS(map_lat.meta_value)) * COS(\n RADIANS(map_lng.meta_value) - RADIANS( %s )\n ) + SIN(RADIANS( %s )) * SIN(RADIANS(map_lat.meta_value))\n )\n ) AS distance\n FROM $wpdb->posts p\n INNER JOIN $wpdb->postmeta map_lat ON p.ID = map_lat.post_id\n INNER JOIN $wpdb->postmeta map_lng ON p.ID = map_lng.post_id\n WHERE 1 = 1\n AND p.post_type = 'beaches'\n AND p.post_status = 'publish'\n AND map_lat.meta_key = 'geo_lat'\n AND map_lng.meta_key = 'geo_lng'\n HAVING distance < %s\n ORDER BY distance ASC\",\n $earth_radius,\n $lat,\n $lng,\n $lat,\n $radius\n );\n\n // Uncomment to echo, paste into phpMyAdmin, and debug.\n // echo $sql;\n\n $nearbyLocations = $wpdb->get_results( $sql );\n\n if ( $nearbyLocations ) {\n return $nearbyLocations;\n }\n }\n</code></pre>\n"
}
] |
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>\n<li>If you only render the shortcode on a product page, then write <code>global $product;</code> at the beginning of your function.</li>\n<li>Else you need to define which product to take: <code>global $product; $product_obj = new WC_Product_Factory(); $product = $product_obj->get_product( \"insert product id\" );</code>. Also write this at the beginning of the function.</li>\n</ul>\n"
},
{
"answer_id": 243826,
"author": "Asisten",
"author_id": 88402,
"author_profile": "https://wordpress.stackexchange.com/users/88402",
"pm_score": 2,
"selected": false,
"text": "<p>I solved this with dirty way.. hope someone else can provide more efficient solution, my final working code for problem above:</p>\n\n<pre><code>$shortkode = '[zendesk_request_form size=\"3\" group=\"extra-field\" subject=\"Quotation For -wkwkwk-\"]';\n$shortkode = do_shortcode( $shortkode );\nadd_action('woocommerce_single_product_summary', 'quotation_form', 61);\nfunction quotation_form()\n{\n$produk = get_the_title();\nglobal $shortkode;\n$shortkode = str_replace(\"-wkwkwk-\", $produk, $shortkode);\necho $shortkode;\n}\n</code></pre>\n\n<p>So i move out do_shorcode outside function, then declare it as global variable.\nThe 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</p>\n"
}
] |
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://developer.wordpress.org/reference/functions/wp_widget_control/\" rel=\"nofollow\"><code>wp_widget_control</code></a> function:</p>\n\n<pre><code>$widget_title = esc_html( strip_tags( $sidebar_args['widget_name'] ) );\n</code></pre>\n\n<p>Now, there is no apparent way to intercept <code>strip_tags</code>, because it is a php function, but <a href=\"https://developer.wordpress.org/reference/functions/esc_html/\" rel=\"nofollow\"><code>esc_html</code></a> is a WP function, that has a filter. So, we cannot prevent the icon/html being stripped, but we can add it back again using the filter. Like this:</p>\n\n<pre><code>add_filter ('esc_html','wpse243718_add_icon_to_widget_name');\n\nfunction wpse243718_add_icon_to_widget_name ($safe_text) {\n global $theme_icon;\n global $theme_name;\n global $pagenow;\n if ( ($pagenow == 'widgets.php') && (substr($safe_text, 0, strlen($theme_name)) == $theme_name) )\n return $theme_icon . ' ' . $safe_text;\n else\n return $safe_text;\n }\n</code></pre>\n\n<p>This code assumes the widget name starts with <code>$theme_name</code>, but you could use other ways of detection as well, of course, or stuff your title with all kinds of html.</p>\n"
},
{
"answer_id": 244667,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Just as @MarkKaplun <a href=\"https://wordpress.stackexchange.com/questions/243718/can-i-individually-style-items-in-the-backend-widget-list/244667#comment363657_243719\">mentioned</a> in a comment, it's possible with CSS. Also with Javascript.</p>\n\n<h2>CSS Approach</h2>\n\n<p>Let's look at the <em>Calendar</em> widget, as an example.</p>\n\n<p>The <em>id</em> for the widget, in the <em>available widgets</em> list, is of the form:</p>\n\n<pre><code>widget-{integer}_calendar-__i__\n</code></pre>\n\n<p>and in the sidebar it's:</p>\n\n<pre><code>widget-{integer}_calendar-{integer}\n</code></pre>\n\n<p>If we want to display the <a href=\"https://developer.wordpress.org/resource/dashicons/#calendar\" rel=\"nofollow noreferrer\">calendar dashicon</a> before the widget title, then we can e.g. enqueue a custom stylesheet for the <code>widgets.php</code> file, with something like:</p>\n\n<pre><code>div[id*=\"_calendar-\"].widget .widget-title h3:before{ \n content: \"\\f145\"; font-family: dashicons; margin-right: 0.5rem; \n}\n</code></pre>\n\n<p>Here we use <code>*=</code> to find a substring match within the id selector.</p>\n\n<p>It will display like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ao32U.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ao32U.jpg\" alt=\"calendar\"></a></p>\n\n<p>If needed we could restrict this further to the <em>right</em> or <em>left</em> parts:</p>\n\n<pre><code>#widgets-right\n#widgets-left\n</code></pre>\n\n<p>or the available widgets:</p>\n\n<pre><code>#available-widgets\n</code></pre>\n\n<p>The <code>widgets.php</code> page will also have <code>body.widgets-php</code> if needed for general stylesheets.</p>\n"
}
] |
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>\n\n<pre><code>$args = array(\n 'post_type' => array('post_type_1', 'post_type_2'), \n 'posts_per_page' => -1,\n 'post_status' => 'publish',\n 'taxonomy-slug' => 'category-slug'\n);\n$query = new WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 243749,
"author": "Kris",
"author_id": 105539,
"author_profile": "https://wordpress.stackexchange.com/users/105539",
"pm_score": 0,
"selected": false,
"text": "<p>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:</p>\n\n<p>Query post by taxonomy tag 'light':</p>\n\n<pre><code>$args = array(\n 'post_type' => array( 'projects' , 'post' ),\n 'tax_query' => array(\n 'relation' => 'OR',\n array(\n 'taxonomy' => 'post_tag',\n 'field' => 'name',\n 'terms' => 'light'\n )\n ),\n 'post_status' => 'publish'\n);\n\nquery_posts( $args );\n</code></pre>\n\n<p>Add tag 'light' to all projects on publish:</p>\n\n<pre><code>add_action('publish_projects', 'projects_post_type_tagging', 10, 2);\n\nfunction projects_post_type_tagging($post_id, $post){\n wp_set_post_terms( $post_id, 'light', 'post_tag', true );\n}\n</code></pre>\n\n<p>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. </p>\n"
},
{
"answer_id": 243751,
"author": "roscabgdn",
"author_id": 78697,
"author_profile": "https://wordpress.stackexchange.com/users/78697",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the WP_Query paramether tag__in to show posts associated with that tag. \nYou can read it here : <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters</a></p>\n"
}
] |
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 specified nav menu.</p>\n\n<pre><code>add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);\n\nfunction special_nav_class($classes, $item){\n $classes[] = 'your-custom-class';\n return $classes;\n}\n</code></pre>\n\n<p>More info: <a href=\"http://www.wpbeginner.com/wp-tutorials/add-a-custom-class-in-wordpress-menu-item-using-conditional-statements/\" rel=\"nofollow\">http://www.wpbeginner.com/wp-tutorials/add-a-custom-class-in-wordpress-menu-item-using-conditional-statements/</a></p>\n"
},
{
"answer_id": 243747,
"author": "roscabgdn",
"author_id": 78697,
"author_profile": "https://wordpress.stackexchange.com/users/78697",
"pm_score": 0,
"selected": false,
"text": "<p>From WordPress Plugin API You can use nav_menu_css_class filter example : </p>\n\n<pre><code>function my_special_nav_class( $classes, $item ) {\n if ( is_single() && $item->title == 'Blog' ) {\n $classes[] = 'special-class';\n }\n return $classes;\n }\n add_filter( 'nav_menu_css_class', 'my_special_nav_class', 10, 2 );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_css_class\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_css_class</a></p>\n"
}
] |
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\">WordPress Multisite</a> which means all your domains share the same <code>wp-config.php</code>.</p>\n\n<p>If this is the case, you can limit SSL to only that one domain by wrapping an <code>if</code> statement around the <code>define( 'FORCE_SSL_ADMIN', true )</code>.</p>\n\n<p><strong>NOTE:</strong> Make sure to change the <code>domain.com</code> to whatever your true SSL website domain name is.</p>\n\n<pre><code>if ( 'domain.com' == $_SERVER['HTTP_HOST'] ) {\n define( 'FORCE_SSL_ADMIN', true );\n}\n</code></pre>\n"
},
{
"answer_id": 266268,
"author": "dpruth",
"author_id": 78022,
"author_profile": "https://wordpress.stackexchange.com/users/78022",
"pm_score": 1,
"selected": true,
"text": "<p>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.</p>\n\n<p>The solution: I purchased a Wildcard certificate, and installed it on multiple servers for each subdomain.</p>\n"
}
] |
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_settings_fields</code> and <code>do_settings_sections</code> in the options-permalink.php between line 226 and 232 for the <code>optional</code> section.</p>\n\n<pre><code>...\n </tr>\n <?php do_settings_fields('permalink', 'optional'); ?>\n</table>\n\n<?php do_settings_sections('permalink'); ?>\n\n<?php submit_button(); ?>\n...\n</code></pre>\n\n<p>The WordPress functions <code>add_settings_field</code> and <code>add_settings_section</code> are using the <a href=\"https://codex.wordpress.org/Settings_API\" rel=\"nofollow\">settings api</a>. In the core files are the <code>do_settings_fields</code> and <code>do_settings_sections</code> functions which will add custom fields or sections (which u added with this api). These are required to place anything in a page. Also these functions are only placed (hardcoded) in the options section of the permalink page. You dont have an access-point in the geneal section like for the options section.</p>\n"
},
{
"answer_id": 243832,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 0,
"selected": false,
"text": "<p>You might just be missing the <a href=\"https://codex.wordpress.org/Function_Reference/add_settings_section\" rel=\"nofollow\"><code>add_settings_section</code></a> before <a href=\"https://codex.wordpress.org/Function_Reference/add_settings_field\" rel=\"nofollow\"><code>add_settings_field</code></a>. This works, and saves the field to an <a href=\"https://codex.wordpress.org/Function_Reference/update_option\" rel=\"nofollow\"><code>option</code></a>, but I might button up that portion. I just wanted to hook earlier than the checks in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/options-permalink.php\" rel=\"nofollow\"><code>options-permalink.php</code></a>.</p>\n\n<pre><code><?php\n\n// ADD SETTINGS\n\nadd_action('admin_head', function(){\n\n // Create a section after the permalink\n\n add_settings_section(\n 'permalink_relative_setting_section_options', // id\n __( 'Protocol Relative URL', 'textdomain' ), // title\n 'premalink_relative_setting_section_callback_function', // callback\n 'permalink' // page\n );\n\n // Add a field to the section\n\n add_settings_field(\n 'permalink_relative_settings_field-id', // id\n '', // title\n 'permalink_relative_settings_field_callback', // callback\n 'permalink', // page\n 'permalink_relative_setting_section_options', // section\n array( 'some_arg' => 'For use in the callback' ) // args\n );\n\n});\n\n// SECTION\n\nfunction premalink_relative_setting_section_callback_function( $args ) {\n\n // Echo SECTION intro text here\n\n /*\n echo '<p>id: ' . esc_html( $args['id'] ) . '</p>'; // id: eg_setting_section\n echo '<p>title: ' . apply_filters( 'the_title', $args['title'] ) . '</p>'; // title: Example settings section in reading\n echo '<p>callback: ' . esc_html( $args['callback'] ) . '</p>'; // callback: eg_setting_section_callback_function\n */\n}\n\n// FIELD\n\nfunction permalink_relative_settings_field_callback( $args ) {\n\n $options = get_option( 'permalink_relative_setting_section_options' );\n\n $html = '<input type=\"checkbox\" id=\"relative_checkbox\" name=\"permalink_relative_setting_section_options[relative_checkbox]\" value=\"1\"' . checked( 1, $options[ 'relative_checkbox' ], false ) . '/>';\n\n $html .= '<label for=\"relative_checkbox\">Do not apply to external links</label>';\n\n echo $html;\n}\n\n// UPDATE\n\nadd_action( 'init', function() {\n\n // If permalink structure is detected, let's update our option before the page can act\n\n if ( isset( $_POST[ 'permalink_structure' ] ) || isset( $_POST[ 'category_base' ] ) ) {\n\n check_admin_referer( 'update-permalink' );\n\n $options = get_option( 'permalink_relative_setting_section_options' );\n\n $options[ 'relative_checkbox' ] = ( isset( $_POST[ 'permalink_relative_setting_section_options' ][ 'relative_checkbox' ] ) && $_POST[ 'permalink_relative_setting_section_options' ][ 'relative_checkbox' ] === '1' )\n ? '1' // checked\n : '';\n\n update_option( 'permalink_relative_setting_section_options', $options );\n }\n} );\n</code></pre>\n\n<h2>Alternate</h2>\n\n<p>If you look at <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/options-permalink.php#L178\" rel=\"nofollow\">https://github.com/WordPress/WordPress/blob/master/wp-admin/options-permalink.php#L178</a> there aren't any hooks to do what you want you want.</p>\n\n<p>Consider jQuery's <a href=\"http://api.jquery.com/category/manipulation/\" rel=\"nofollow\">manipulation</a> methods like <a href=\"http://api.jquery.com/detach/\" rel=\"nofollow\"><code>detach</code></a> and <a href=\"http://api.jquery.com/insertAfter/\" rel=\"nofollow\"><code>insertAfter</code></a> which you could utilize in the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_footer\" rel=\"nofollow\"><code>admin_footer</code></a>.</p>\n\n<pre><code>jQuery('<h1>Protocol Relative URL Form!</h1>').insertAfter('.form-table.permalink-structure');\n</code></pre>\n"
},
{
"answer_id": 243866,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 2,
"selected": true,
"text": "<p>Figured it out by using the following jQuery function. The <code>#protocol_relative</code> is the field I am inserting and <code>#home-description</code> is the field I am inserting it after:</p>\n\n<pre><code>add_action( 'admin_footer', 'insert_field' );\nfunction insert_field() {\n # Insert the settings field after the 'Site Address (URL)'\n ?> <script type=\"text/javascript\">\n jQuery( '#protocol_relative' ).closest( 'tr' ).insertAfter( jQuery( '#home-description' ).closest( 'tr' ) );\n </script> <?php\n}\n</code></pre>\n"
}
] |
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 see if those save. </p>\n\n<pre><code>$tmp_mail_smtp = 'Test Mail SMTP';\n$tmp_mail_smtp_host = 'Test Mail SMTP Host';\n$tmp_mail_smtp_auth = 'Test Mail SMTP Auth';\n\n$my_update = $wpdb->update( $wpdb->prefix . 'my_settings',\n array( 'value' => $tmp_mail_smtp,\n 'value' => $tmp_mail_smtp_host,\n 'value' => $tmp_mail_smtp_auth,\n ),\n array( 'name' => 'mail-smtp',\n 'name' => 'mail-smtp-host',\n 'name' => 'mail-smtp-auth',\n )\n);\n</code></pre>\n\n<p><strong>Update #1</strong></p>\n\n<p>Since the above doesn't work for you, remove the <code>$wpdb->update</code> code and try updating each option separately and see if that works.</p>\n\n<pre><code>if ( $settings_message == '0' ) {\n update_option( 'role', $tmp_role );\n update_option( 'mail-smtp', $tmp_mail_smtp );\n update_option( 'mail-smtp-host', $tmp_mail_smtp_host );\n update_option( 'mail-smtp-auth', $tmp_mail_smtp_auth );\n}\n</code></pre>\n\n<p>P.S. Since this is a wp-admin page, I'd read more about the <a href=\"https://codex.wordpress.org/Settings_API\" rel=\"nofollow\">Settings API</a> which provides a more structured way of adding/managing option pages.</p>\n"
},
{
"answer_id": 244200,
"author": "wassereimer",
"author_id": 54551,
"author_profile": "https://wordpress.stackexchange.com/users/54551",
"pm_score": 2,
"selected": true,
"text": "<p>I googled a lot the last days and a few times i´ve seen postings that say that the <code>$wpdb->update</code> function doens´t support multiple updates and that this is not well documented. -> Sorry i don´t have links anymore...</p>\n\n<p>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.</p>\n\n<p>The function:</p>\n\n<pre><code>function update_queries( $queries ) {\n global $wpdb;\n\n // set array\n $error = array();\n\n // run update commands\n foreach( $queries as $query ) {\n $query = str_replace( '[wp-prefix]', $wpdb->prefix, $query );\n $last_error = $wpdb->last_error;\n $wpdb->query( $query );\n\n // fill array when we have an error\n if( (empty( $wpdb->result ) || !$wpdb->result ) && !empty( $wpdb->last_error ) && $last_error != $wpdb->last_error ) {\n $error[]= $wpdb->last_error.\" ($query)\";\n }\n }\n\n // when we have an error\n if( $error ) {\n return $error;\n\n // when everything is fine\n }else{\n return false;\n }\n}\n</code></pre>\n\n<p>If we want to update a few things:</p>\n\n<pre><code>// update database\n$queries = array();\n$queries[] = \"UPDATE `[wp-prefix]table` SET `value` = '$value' WHERE `name` = 'name';\";\n$queries[] = \"UPDATE `[wp-prefix]table` SET `value` = '$value2' WHERE `name` = 'name2';\";\n$error = update_queries( $queries );\n\n// if we have an error\nif( !empty( $error ) ) {\n .....\n\n// when everything is fine\n}else{\n .....\n}\n</code></pre>\n"
}
] |
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 see if those save. </p>\n\n<pre><code>$tmp_mail_smtp = 'Test Mail SMTP';\n$tmp_mail_smtp_host = 'Test Mail SMTP Host';\n$tmp_mail_smtp_auth = 'Test Mail SMTP Auth';\n\n$my_update = $wpdb->update( $wpdb->prefix . 'my_settings',\n array( 'value' => $tmp_mail_smtp,\n 'value' => $tmp_mail_smtp_host,\n 'value' => $tmp_mail_smtp_auth,\n ),\n array( 'name' => 'mail-smtp',\n 'name' => 'mail-smtp-host',\n 'name' => 'mail-smtp-auth',\n )\n);\n</code></pre>\n\n<p><strong>Update #1</strong></p>\n\n<p>Since the above doesn't work for you, remove the <code>$wpdb->update</code> code and try updating each option separately and see if that works.</p>\n\n<pre><code>if ( $settings_message == '0' ) {\n update_option( 'role', $tmp_role );\n update_option( 'mail-smtp', $tmp_mail_smtp );\n update_option( 'mail-smtp-host', $tmp_mail_smtp_host );\n update_option( 'mail-smtp-auth', $tmp_mail_smtp_auth );\n}\n</code></pre>\n\n<p>P.S. Since this is a wp-admin page, I'd read more about the <a href=\"https://codex.wordpress.org/Settings_API\" rel=\"nofollow\">Settings API</a> which provides a more structured way of adding/managing option pages.</p>\n"
},
{
"answer_id": 244200,
"author": "wassereimer",
"author_id": 54551,
"author_profile": "https://wordpress.stackexchange.com/users/54551",
"pm_score": 2,
"selected": true,
"text": "<p>I googled a lot the last days and a few times i´ve seen postings that say that the <code>$wpdb->update</code> function doens´t support multiple updates and that this is not well documented. -> Sorry i don´t have links anymore...</p>\n\n<p>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.</p>\n\n<p>The function:</p>\n\n<pre><code>function update_queries( $queries ) {\n global $wpdb;\n\n // set array\n $error = array();\n\n // run update commands\n foreach( $queries as $query ) {\n $query = str_replace( '[wp-prefix]', $wpdb->prefix, $query );\n $last_error = $wpdb->last_error;\n $wpdb->query( $query );\n\n // fill array when we have an error\n if( (empty( $wpdb->result ) || !$wpdb->result ) && !empty( $wpdb->last_error ) && $last_error != $wpdb->last_error ) {\n $error[]= $wpdb->last_error.\" ($query)\";\n }\n }\n\n // when we have an error\n if( $error ) {\n return $error;\n\n // when everything is fine\n }else{\n return false;\n }\n}\n</code></pre>\n\n<p>If we want to update a few things:</p>\n\n<pre><code>// update database\n$queries = array();\n$queries[] = \"UPDATE `[wp-prefix]table` SET `value` = '$value' WHERE `name` = 'name';\";\n$queries[] = \"UPDATE `[wp-prefix]table` SET `value` = '$value2' WHERE `name` = 'name2';\";\n$error = update_queries( $queries );\n\n// if we have an error\nif( !empty( $error ) ) {\n .....\n\n// when everything is fine\n}else{\n .....\n}\n</code></pre>\n"
}
] |
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 see if those save. </p>\n\n<pre><code>$tmp_mail_smtp = 'Test Mail SMTP';\n$tmp_mail_smtp_host = 'Test Mail SMTP Host';\n$tmp_mail_smtp_auth = 'Test Mail SMTP Auth';\n\n$my_update = $wpdb->update( $wpdb->prefix . 'my_settings',\n array( 'value' => $tmp_mail_smtp,\n 'value' => $tmp_mail_smtp_host,\n 'value' => $tmp_mail_smtp_auth,\n ),\n array( 'name' => 'mail-smtp',\n 'name' => 'mail-smtp-host',\n 'name' => 'mail-smtp-auth',\n )\n);\n</code></pre>\n\n<p><strong>Update #1</strong></p>\n\n<p>Since the above doesn't work for you, remove the <code>$wpdb->update</code> code and try updating each option separately and see if that works.</p>\n\n<pre><code>if ( $settings_message == '0' ) {\n update_option( 'role', $tmp_role );\n update_option( 'mail-smtp', $tmp_mail_smtp );\n update_option( 'mail-smtp-host', $tmp_mail_smtp_host );\n update_option( 'mail-smtp-auth', $tmp_mail_smtp_auth );\n}\n</code></pre>\n\n<p>P.S. Since this is a wp-admin page, I'd read more about the <a href=\"https://codex.wordpress.org/Settings_API\" rel=\"nofollow\">Settings API</a> which provides a more structured way of adding/managing option pages.</p>\n"
},
{
"answer_id": 244200,
"author": "wassereimer",
"author_id": 54551,
"author_profile": "https://wordpress.stackexchange.com/users/54551",
"pm_score": 2,
"selected": true,
"text": "<p>I googled a lot the last days and a few times i´ve seen postings that say that the <code>$wpdb->update</code> function doens´t support multiple updates and that this is not well documented. -> Sorry i don´t have links anymore...</p>\n\n<p>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.</p>\n\n<p>The function:</p>\n\n<pre><code>function update_queries( $queries ) {\n global $wpdb;\n\n // set array\n $error = array();\n\n // run update commands\n foreach( $queries as $query ) {\n $query = str_replace( '[wp-prefix]', $wpdb->prefix, $query );\n $last_error = $wpdb->last_error;\n $wpdb->query( $query );\n\n // fill array when we have an error\n if( (empty( $wpdb->result ) || !$wpdb->result ) && !empty( $wpdb->last_error ) && $last_error != $wpdb->last_error ) {\n $error[]= $wpdb->last_error.\" ($query)\";\n }\n }\n\n // when we have an error\n if( $error ) {\n return $error;\n\n // when everything is fine\n }else{\n return false;\n }\n}\n</code></pre>\n\n<p>If we want to update a few things:</p>\n\n<pre><code>// update database\n$queries = array();\n$queries[] = \"UPDATE `[wp-prefix]table` SET `value` = '$value' WHERE `name` = 'name';\";\n$queries[] = \"UPDATE `[wp-prefix]table` SET `value` = '$value2' WHERE `name` = 'name2';\";\n$error = update_queries( $queries );\n\n// if we have an error\nif( !empty( $error ) ) {\n .....\n\n// when everything is fine\n}else{\n .....\n}\n</code></pre>\n"
}
] |
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 calling the child theme's <code>index.php</code> over parent theme's <code>index.php</code>. And you have nothing on <code>index.php</code>. So the site is showing nothing. Delete the child theme's <code>index.php</code>. You'll see the site live.</p>\n"
},
{
"answer_id": 276990,
"author": "Jitender Singh",
"author_id": 110753,
"author_profile": "https://wordpress.stackexchange.com/users/110753",
"pm_score": 1,
"selected": false,
"text": "<hr>\n\n<pre><code>*\n Theme Name: Twenty Fifteen Child\n Theme URI: http://example.com/twenty-fifteen-child/\n Description: Twenty Fifteen Child Theme\n Author: John Doe\n Author URI: http://example.com\n Template: twentyfifteen\n Version: 1.0.0\n License: GNU General Public License v2 or later\n License URI: http://www.gnu.org/licenses/gpl-2.0.html\n Tags: light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready\n Text Domain: twenty-fifteen-child\n*/\n</code></pre>\n\n<hr>\n\n<p>See carefully wordpress coding standard. You have forgot define <strong>Template</strong> of your parents theme. Please define <strong>Template</strong> of your parent theme and then see.\nHope this will help!</p>\n"
}
] |
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 documentation:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_queried_object</a></p>\n"
},
{
"answer_id": 243860,
"author": "Matthew",
"author_id": 54053,
"author_profile": "https://wordpress.stackexchange.com/users/54053",
"pm_score": 0,
"selected": false,
"text": "<p>Put your $c term (in your loop) in a <a href=\"http://php.net/manual/en/function.print-r.php\" rel=\"nofollow\">print_r</a>/<a href=\"http://php.net/manual/en/function.var-dump.php\" rel=\"nofollow\">var_dump</a> to see if the property you are trying to compare the values of is of the actual value that you are looking for\n(See below).</p>\n\n<p>I've also added a ternary operator in the place of your if statement, it is just better practice. (Read below for more on ternary operators).</p>\n\n<pre><code><menu id=\"nav\">\n <ul> \n <?php $cat_id = get_cat_ID();\n foreach( $categories as $c ):?>\n <?php print_r($c); ?> \n <li class=\"<?php echo $c->term_id == $cat_id ? 'active' : null ;} ?>\">\n <a href=\"<?php echo get_category_link( $c->term_id ); ?>\" title=\"<?php echo $c->cat_name ;?>\">\n <?php echo $c->cat_name ;?>\n </a> \n </li>\n <?php endforeach; ?> \n </ul>\n</menu>\n</code></pre>\n\n<p><strong>Ternary Operator</strong></p>\n\n<p>In computer programming, ?: is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if.</p>\n\n<pre><code>if(1==1) echo 'true'; \nelse echo 'false';\n</code></pre>\n\n<p>can be done in a ternary operator like so:</p>\n\n<pre><code>echo 1==1 ? 'true' : 'false';\n</code></pre>\n\n<p>Another example</p>\n\n<pre><code>if(1==1) $boolean = true;\nelse $boolean = false;\n</code></pre>\n\n<p>can be done in a ternary operator like so:</p>\n\n<pre><code>$boolean = 1==1 ? true : false;\n</code></pre>\n\n<p>Since PHP 5.3, the 'middle part' of the operator can be left out.\nShorthand ternary operators can be used to match only false</p>\n\n<pre><code>if(1!=2) echo 'false';\n</code></pre>\n\n<p>The ternary operator:</p>\n\n<pre><code>echo 1!=2 ?: 'false';\n</code></pre>\n\n<p>Read more:\n<a href=\"http://php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow\">http://php.net/manual/en/language.operators.comparison.php</a></p>\n"
}
] |
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 the function. It'll look like below-</p>\n\n<pre><code>add_action('wp_logout', 'wc_registration_redirect');\n\nfunction wc_registration_redirect( $redirect_to) {\n wp_redirect( '/my-account');\n exit;\n}\n</code></pre>\n"
},
{
"answer_id": 243893,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>The correct method for changing the logout redirect is the <code>logout_redirect</code> filter:</p>\n\n<pre><code>/**\n * Filters the log out redirect URL.\n *\n * @since 4.2.0\n *\n * @param string $redirect_to The redirect destination URL.\n * @param string $requested_redirect_to The requested redirect destination URL passed as a parameter.\n * @param WP_User $user The WP_User object for the user that's logging out.\n */\nadd_filter( 'logout_redirect', function( $redirect_to, $requested_redirect_to, $user ) {\n if ( ! $requested_redirect_to ) { // Don't override the redirect if one was already set in the logout URL\n $redirect = home_url( user_trailingslashit( 'my-account' ) );\n }\n\n return $redirect;\n}, 10, 3 );\n</code></pre>\n"
}
] |
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 the function. It'll look like below-</p>\n\n<pre><code>add_action('wp_logout', 'wc_registration_redirect');\n\nfunction wc_registration_redirect( $redirect_to) {\n wp_redirect( '/my-account');\n exit;\n}\n</code></pre>\n"
},
{
"answer_id": 243893,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>The correct method for changing the logout redirect is the <code>logout_redirect</code> filter:</p>\n\n<pre><code>/**\n * Filters the log out redirect URL.\n *\n * @since 4.2.0\n *\n * @param string $redirect_to The redirect destination URL.\n * @param string $requested_redirect_to The requested redirect destination URL passed as a parameter.\n * @param WP_User $user The WP_User object for the user that's logging out.\n */\nadd_filter( 'logout_redirect', function( $redirect_to, $requested_redirect_to, $user ) {\n if ( ! $requested_redirect_to ) { // Don't override the redirect if one was already set in the logout URL\n $redirect = home_url( user_trailingslashit( 'my-account' ) );\n }\n\n return $redirect;\n}, 10, 3 );\n</code></pre>\n"
}
] |
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-everything/\" rel=\"nofollow\">https://wordpress.org/plugins/search-everything/</a></p>\n\n<p>Or this one is better, but you got pay <a href=\"https://searchwp.com/\" rel=\"nofollow\">https://searchwp.com/</a>. You can specify custom fields to search or shortcodes.</p>\n\n<p>If your text is not on database you should use Google Custom Search Engine inside your website</p>\n"
},
{
"answer_id": 243965,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": true,
"text": "<h1>Use <a href=\"https://markjs.io/\" rel=\"nofollow noreferrer\">mark.js</a>, a jQuery plugin</h1>\n\n<p><a href=\"https://markjs.io/\" rel=\"nofollow noreferrer\">mark.js</a> 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:</p>\n\n<ul>\n<li>search for keywords separately instead of the complete term</li>\n<li>map diacritics (For example if \"justo\" should also match \"justò\")</li>\n<li>ignore matches inside custom elements</li>\n<li>use custom highlighting element</li>\n<li>use custom highlighting class</li>\n<li>map custom synonyms</li>\n<li>search also inside iframes</li>\n<li>receive not found terms</li>\n</ul>\n\n<p><strong><a href=\"https://markjs.io/configurator.html\" rel=\"nofollow noreferrer\">DEMO</a></strong></p>\n\n<p>Alternatively you can see <a href=\"https://jsfiddle.net/julmot/vpav6tL1/\" rel=\"nofollow noreferrer\">this fiddle</a>.</p>\n\n<p><strong>Usage example</strong>:</p>\n\n<pre><code>// Highlight \"keyword\" in the specified context\n$(\".context\").mark(\"keyword\");\n\n// Highlight the custom regular expression in the specified context\n$(\".context\").markRegExp(/Lorem/gmi);\n</code></pre>\n\n<p>It's free and developed open-source on GitHub (<a href=\"https://github.com/julmot/mark.js\" rel=\"nofollow noreferrer\">project reference</a>).</p>\n\n<h1>Example of mark.js keyword highlighting with your code</h1>\n\n\n\n<pre class=\"lang-js prettyprint-override\"><code>$(function() {\n $(\"input\").on(\"input.highlight\", function() {\n // Determine specified search term\n var searchTerm = $(this).val();\n // Highlight search term inside a specific context\n $(\"#context\").unmark().mark(searchTerm);\n }).trigger(\"input.highlight\").focus();\n});\n</code></pre>\n\n<pre class=\"lang-css prettyprint-override\"><code>mark {\n background: orange;\n color: black;\n}\n</code></pre>\n\n<pre class=\"lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/mark.js/7.0.0/jquery.mark.min.js\"></script>\n<input type=\"text\" value=\"test\">\n<div id=\"context\">\n Lorem ipsum dolor test sit amet\n</div>\n</code></pre>\n\n\n\n<p>I found the answer <a href=\"https://stackoverflow.com/questions/10011385/jquery-search-in-static-html-page-with-highlighting-of-found-word\">here</a>. You can find plenty of other answer there also. But I prefer to use a <code>jQuery</code> plugin. The reason is given below-</p>\n\n<h1>Why using a selfmade highlighting function is a bad idea</h1>\n\n<p>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:</p>\n\n<ul>\n<li>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. <code>innerHTML</code>)</li>\n<li>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.</li>\n<li>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!</li>\n</ul>\n\n<p>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.</p>\n\n<p>When using an existing, well implemented plugin, you don't have to worry about above named things.</p>\n\n<p>Hope that thing helps you.</p>\n"
}
] |
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 opinion) to do this is via the CDN.\nI use the following:</p>\n\n<pre><code>// Add font awesome & bootstrap\nfunction awesome_css() {\n wp_enqueue_style(\"fontawesome\", 'https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css');\n wp_enqueue_style(\"bootstrap3\", 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');\n }\nadd_action( 'wp_enqueue_scripts', 'awesome_css' );\n</code></pre>\n\n<p>This goes into your functions.php file. </p>\n\n<p>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 <a href=\"http://fontawesome.io/cheatsheet/\" rel=\"nofollow\">fontawesome cheat sheet</a></p>\n\n<p>Refer to the examples on fontawesome for more info.</p>\n"
},
{
"answer_id": 243995,
"author": "Grim",
"author_id": 104433,
"author_profile": "https://wordpress.stackexchange.com/users/104433",
"pm_score": 0,
"selected": false,
"text": "<p>Solved: The font in Jetpack is called social-logos and is used like this : <code>font: 400 18px/1 social-logos; content: \"\\f203\";</code></p>\n"
}
] |
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. See the changes in the code below:</p>\n\n<pre><code>function create_reviews_post_type() {\n register_post_type('acme_reviews', array(\n 'labels' => array(\n 'name' => __('Reviews'),\n 'singular_name' => __('Review')\n ),\n 'menu_position' => 5,\n 'public' => true,\n 'has_archive' => 'reviews',\n );\n}\nadd_action('init', 'create_reviews_post_type');\n</code></pre>\n"
},
{
"answer_id": 243919,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>According to the codex (and what works for me!) is to just use a rewrite in the array. Both options work but wordpress suggests using the rewrite Below is the quote directly from the codex:</p>\n\n<blockquote>\n <p>has_archive\n (boolean or string) (optional) Enables post type archives. Will use $post_type as archive slug by default.</p>\n \n <p>Default: false </p>\n \n <p>Note: Will generate the proper rewrite rules if rewrite is enabled. <strong>Also use rewrite to change the slug used</strong>.</p>\n</blockquote>\n\n<p>MAKE SURE TO FLUSH THE PERMALINK RULES. \nif this is in a plugin i always suggest adding an init that flushes the rules when the plugin is activated.</p>\n\n<p>Here is the code, notice i customized the function name too for the same reasons that you customize the post name itself.</p>\n\n<pre><code>function create_acme_reviews_post_type() { //namespaced your function too..\n register_post_type('acme_reviews', array(\n 'labels' => array(\n 'name' => __('Reviews'),\n 'singular_name' => __('Review')\n ),\n 'menu_position' => 5,\n 'public' => true,\n 'has_archive' => true,\n 'rewrite' => array( 'slug' => 'reviews' ), //changes permalink structure\n )\n );\n}\nadd_action('init', 'create_acme_reviews_post_type'); //namespaced function call too..\n</code></pre>\n"
}
] |
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-editor/\" rel=\"nofollow\">this one</a> is one of them.</p>\n\n<p>Also, those are not \"posts\", they are backend panel menu items.</p>\n"
},
{
"answer_id": 244010,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 1,
"selected": false,
"text": "<p>You can re order admin left menu by below code:</p>\n\n<pre><code>/*\n * Code below groups Dashboard/Posts/Pages/Comments together at the top of the dashboard menu.\n * If you were to have a custom type that you want to add to the group use the following edit.php?post_type=YOURPOSTTYPENAME\n */\nfunction reorder_my_admin_menu( $__return_true ) {\n return array(\n 'index.php', // Dashboard\n 'edit.php?post_type=page', // Pages \n 'edit.php', // Posts\n 'upload.php', // Media\n 'themes.php', // Appearance\n 'separator1', // --Space--\n 'edit-comments.php', // Comments \n 'users.php', // Users\n 'separator2', // --Space--\n 'plugins.php', // Plugins\n 'tools.php', // Tools\n 'options-general.php', // Settings\n );\n}\nadd_filter( 'custom_menu_order', 'reorder_my_admin_menu' );\nadd_filter( 'menu_order', 'reorder_my_admin_menu' ); \n</code></pre>\n\n<p>Above code used <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/custom_menu_order\" rel=\"nofollow\">custom_menu_order</a> and <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/menu_order\" rel=\"nofollow\">menu_order</a> hook to re order existing menu items. Hope this help you well!</p>\n"
}
] |
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!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.