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
|
---|---|---|---|---|---|---|
199,427 |
<p>Is there a way to create deep-level sub Panel in Theme Customizer(like roots of plants) ? My theme that I have been developing seem to be more complicated. I think that if we can create deep-level sub Panel, our Customizer Page won't look messy, our user will customize our theme easier and we will be able to make much more complicated WordPress theme easier. Images below describe what my idea is...</p>
<p><a href="https://i.stack.imgur.com/LEjfA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LEjfA.png" alt="Theme Customizer concept that I found on online tutorials"></a>
<a href="https://i.stack.imgur.com/POdKv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/POdKv.png" alt="Here is sub panel that I wan to create"></a></p>
<p>Unfortunately, I have tried to search out about this one, but I could only find a way to create single-level Panel in the Theme Customizer here is what I found on <a href="https://wordpress.stackexchange.com/questions/169919/how-to-create-a-theme-customizer-sub-panel">another thread</a> , couldn't find a way to make sub Panel deeper. Could you please shade some light in my life ?</p>
<p><strong>Update</strong> : following code is some code I use to create Panel and Control like image #1 which is single-level Panel. they all work fine.</p>
<pre><code>$wp_customize->add_panel('panel1',
array(
'title' => 'Panel 1',
'priority' => 1,
)
);
$wp_customize->add_section( 'section1',
array(
'title' => 'This is section 1',
'priority' => 1,
'panel' => 'panel1'
)
);
$wp_customize->add_setting('field1', array('default' => 'default text'));
$wp_customize->add_control('field1', array(
'label' => 'Text field',
'section' => 'section1',
'type' => 'text',
)
);
</code></pre>
<p>My problem is that I want to create new panel and let them stick in another panel which will make it look like roots hierarchy(image #2) I think that if we can do some thing like that, we will be able to make much more powerful Theme Customizer. I then tried to accomplish that idea and tried to rewrite my code. Unluckily, it didn't work. Please check up the following one.</p>
<pre><code>$wp_customize->add_panel('panel1',
array(
'title' => 'Panel 1',
'priority' => 1,
)
);
$wp_customize->add_section( 'section1',
array(
'title' => 'This is section 1',
'priority' => 1,
'panel' => 'panel1'
)
);
$wp_customize->add_setting('field1', array('default' => 'default text'));
$wp_customize->add_control('field1', array(
'label' => 'Text field',
'section' => 'section1',
'type' => 'text',
)
);
// I used the code below with a little hope that it will help me accomplish my idea, but it didn't work T^T.
$wp_customize->add_panel('panel1_1',
array(
'title' => 'Panel 1.1',
'priority' => 2,
'panel' => 'panel1' // I tried adding this line of code in order to let it depend on another panel
)
);
$wp_customize->add_section( 'section1_1',
array(
'title' => 'This is section 1',
'priority' => 1,
'panel' => 'panel1_1'
)
);
$wp_customize->add_setting('field1_1', array('default' => 'default text'));
$wp_customize->add_control('field1_1', array(
'label' => 'Text field',
'section' => 'section1_1',
'type' => 'text',
)
);
</code></pre>
<p>Could you please give me the solution, I can't figure out how to make panel look like roots hierarchy. Any help would be appreciated :)</p>
|
[
{
"answer_id": 226793,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>At the moment it is simply not possible to have more than panels, sections and controls. Expanding this system would require extensive programming at WP. Given the narrow size of the customizer you could also easily get lost if you have so many nested panels. So it's probably not desirable either.</p>\n"
},
{
"answer_id": 256103,
"author": "OriginalEXE",
"author_id": 16710,
"author_profile": "https://wordpress.stackexchange.com/users/16710",
"pm_score": 4,
"selected": true,
"text": "<p>For anyone that comes here looking for this, I was able to do it after battling with it for a few hours.</p>\n\n<p>The code is a bit extensive so did not want to post here, (mods feel free to let me now if that would be better), instead I created a gist: <a href=\"https://gist.github.com/OriginalEXE/9a6183e09f4cae2f30b006232bb154af\" rel=\"noreferrer\">https://gist.github.com/OriginalEXE/9a6183e09f4cae2f30b006232bb154af</a></p>\n\n<p>What it does is it basically allows you yo specify <code>panel</code> property on panels (for nesting panels under panels) and <code>section</code> property on sections (for nesting sections under sections).</p>\n\n<p>Notes:</p>\n\n<ul>\n<li>The php code includes an example of how to create\npanels/sub-panels/sections/sub-sections. It is worth noting that you\ninstantiate new panels/sections using the subclass I created, instead\nof directly calling <code>$wp-customize->add_panel</code> and passing it a\nconfiguration array.</li>\n<li>JS and CSS files don't need to be modified. If you were wondering why CSS is needed, it's there to fix the animation when transitioning from panels to sub-panels and sections to sub-sections.</li>\n<li>When creating sub-sections, make sure you also add a <code>panel</code> property which should be the same as the <code>panel</code> of the parent section</li>\n</ul>\n\n<p>I tried to do this with as little code as possible, and without overriding anything that might screw up with others people code. Some refactoring might be needed if they change logic in the future versions, I made it as future-proof as I could.</p>\n"
}
] |
2015/08/23
|
[
"https://wordpress.stackexchange.com/questions/199427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76562/"
] |
Is there a way to create deep-level sub Panel in Theme Customizer(like roots of plants) ? My theme that I have been developing seem to be more complicated. I think that if we can create deep-level sub Panel, our Customizer Page won't look messy, our user will customize our theme easier and we will be able to make much more complicated WordPress theme easier. Images below describe what my idea is...
[](https://i.stack.imgur.com/LEjfA.png)
[](https://i.stack.imgur.com/POdKv.png)
Unfortunately, I have tried to search out about this one, but I could only find a way to create single-level Panel in the Theme Customizer here is what I found on [another thread](https://wordpress.stackexchange.com/questions/169919/how-to-create-a-theme-customizer-sub-panel) , couldn't find a way to make sub Panel deeper. Could you please shade some light in my life ?
**Update** : following code is some code I use to create Panel and Control like image #1 which is single-level Panel. they all work fine.
```
$wp_customize->add_panel('panel1',
array(
'title' => 'Panel 1',
'priority' => 1,
)
);
$wp_customize->add_section( 'section1',
array(
'title' => 'This is section 1',
'priority' => 1,
'panel' => 'panel1'
)
);
$wp_customize->add_setting('field1', array('default' => 'default text'));
$wp_customize->add_control('field1', array(
'label' => 'Text field',
'section' => 'section1',
'type' => 'text',
)
);
```
My problem is that I want to create new panel and let them stick in another panel which will make it look like roots hierarchy(image #2) I think that if we can do some thing like that, we will be able to make much more powerful Theme Customizer. I then tried to accomplish that idea and tried to rewrite my code. Unluckily, it didn't work. Please check up the following one.
```
$wp_customize->add_panel('panel1',
array(
'title' => 'Panel 1',
'priority' => 1,
)
);
$wp_customize->add_section( 'section1',
array(
'title' => 'This is section 1',
'priority' => 1,
'panel' => 'panel1'
)
);
$wp_customize->add_setting('field1', array('default' => 'default text'));
$wp_customize->add_control('field1', array(
'label' => 'Text field',
'section' => 'section1',
'type' => 'text',
)
);
// I used the code below with a little hope that it will help me accomplish my idea, but it didn't work T^T.
$wp_customize->add_panel('panel1_1',
array(
'title' => 'Panel 1.1',
'priority' => 2,
'panel' => 'panel1' // I tried adding this line of code in order to let it depend on another panel
)
);
$wp_customize->add_section( 'section1_1',
array(
'title' => 'This is section 1',
'priority' => 1,
'panel' => 'panel1_1'
)
);
$wp_customize->add_setting('field1_1', array('default' => 'default text'));
$wp_customize->add_control('field1_1', array(
'label' => 'Text field',
'section' => 'section1_1',
'type' => 'text',
)
);
```
Could you please give me the solution, I can't figure out how to make panel look like roots hierarchy. Any help would be appreciated :)
|
For anyone that comes here looking for this, I was able to do it after battling with it for a few hours.
The code is a bit extensive so did not want to post here, (mods feel free to let me now if that would be better), instead I created a gist: <https://gist.github.com/OriginalEXE/9a6183e09f4cae2f30b006232bb154af>
What it does is it basically allows you yo specify `panel` property on panels (for nesting panels under panels) and `section` property on sections (for nesting sections under sections).
Notes:
* The php code includes an example of how to create
panels/sub-panels/sections/sub-sections. It is worth noting that you
instantiate new panels/sections using the subclass I created, instead
of directly calling `$wp-customize->add_panel` and passing it a
configuration array.
* JS and CSS files don't need to be modified. If you were wondering why CSS is needed, it's there to fix the animation when transitioning from panels to sub-panels and sections to sub-sections.
* When creating sub-sections, make sure you also add a `panel` property which should be the same as the `panel` of the parent section
I tried to do this with as little code as possible, and without overriding anything that might screw up with others people code. Some refactoring might be needed if they change logic in the future versions, I made it as future-proof as I could.
|
199,469 |
<p>How to get shortcode thumbnail size?</p>
<p>my code get shortcode thumbnail size in functions:</p>
<pre><code>function thumb_medium( $atts, $content = null ) {
return wp_get_attachment_url( get_post_thumbnail_id( $post_id, 'medium') );
//or wp_get_attachment_url( get_post_thumbnail_id( $post_id, 'large') );
//or wp_get_attachment_url( get_post_thumbnail_id( $post_id, array(100,100)) );
}
add_shortcode("get_urlthumb", "thumb_medium");
</code></pre>
<p>but [get_urlthumb] always echo full url thumbnail as: <code>wp-content/uploads/2015/08/origin-image-upload.jpg</code></p>
<p>Thanks</p>
|
[
{
"answer_id": 199476,
"author": "Kory",
"author_id": 78199,
"author_profile": "https://wordpress.stackexchange.com/users/78199",
"pm_score": 3,
"selected": true,
"text": "<p>I think your code is very close, try to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src\" rel=\"nofollow\"><code>wp_get_attachment_image_src()</code></a> instead:</p>\n\n<pre><code>function thumb_medium( $atts, $content = null ) {\n // return wp_get_attachment_url( get_post_thumbnail_id( $post_id, 'medium') );\n global $post;\n $thumb_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium' )[0];\n if ($thumb_url) {\n return $thumb_url;\n }\n}\nadd_shortcode(\"get_urlthumb\", \"thumb_medium\");\n</code></pre>\n"
},
{
"answer_id": 199478,
"author": "Ajay Gadhavana",
"author_id": 73949,
"author_profile": "https://wordpress.stackexchange.com/users/73949",
"pm_score": 0,
"selected": false,
"text": "<p>You can also go with <code> aq_resize </code> function.<br>\nThere are second and third arguments are given for size, so you can give any size that's you want. <br>\nEven you can also set these size using shortcode.\nCheck how to pass arguments to shortcode and pass using shortcode if want to fetch dynamic size for each time</p>\n\n<pre><code>function thumb_medium( $atts, $content = null ) {\n $thumb = wp_get_attachment_url( get_post_thumbnail_id( $post_id, 'full') );\n $thumb = aq_resize( $thumb, 400, 400, true ); //resize & crop img\n}\nadd_shortcode(\"get_urlthumb\", \"thumb_medium\");\n</code></pre>\n"
}
] |
2015/08/24
|
[
"https://wordpress.stackexchange.com/questions/199469",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65359/"
] |
How to get shortcode thumbnail size?
my code get shortcode thumbnail size in functions:
```
function thumb_medium( $atts, $content = null ) {
return wp_get_attachment_url( get_post_thumbnail_id( $post_id, 'medium') );
//or wp_get_attachment_url( get_post_thumbnail_id( $post_id, 'large') );
//or wp_get_attachment_url( get_post_thumbnail_id( $post_id, array(100,100)) );
}
add_shortcode("get_urlthumb", "thumb_medium");
```
but [get\_urlthumb] always echo full url thumbnail as: `wp-content/uploads/2015/08/origin-image-upload.jpg`
Thanks
|
I think your code is very close, try to use [`wp_get_attachment_image_src()`](https://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src) instead:
```
function thumb_medium( $atts, $content = null ) {
// return wp_get_attachment_url( get_post_thumbnail_id( $post_id, 'medium') );
global $post;
$thumb_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium' )[0];
if ($thumb_url) {
return $thumb_url;
}
}
add_shortcode("get_urlthumb", "thumb_medium");
```
|
199,496 |
<p>I want an extra sidebar added to this wordpress theme of mine. I want it right under my left sidebar and not next to it as it is currently showing: <a href="http://www.giftforgag.com" rel="nofollow">www.giftforgag.com</a>.</p>
<p>I have tried many things but nothing seems to be working. I have also tried making various changes to the css.</p>
<p>I had thought it would be easiest to simply place <code>get_sidebar('left');</code> right under the <code>get_sidebar();</code> function that exists at the very end but it hasn't worked out.</p>
<p>The theme in question is twenty-fourteen and I have placed the code of the file here:</p>
<pre><code><?php
get_header(); ?>
<div id="main-content" class="main-content">
<?php
if ( is_front_page() && twentyfourteen_has_featured_posts() ) {
get_template_part( 'featured-content' );
}
?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile;
twentyfourteen_paging_nav();
else :
get_template_part( 'content', 'none' );
endif;
?>
</div><!-- #content -->
</div><!-- #primary -->
</div><!-- #main-content -->
<?php
get_sidebar();
get_sidebar('left');
get_footer();
</code></pre>
<p>I have registered the widget using the following code:</p>
<pre><code>function mychild_widgets_init() {
register_sidebar( array(
'name' => __( 'Left Widget Area', 'twentyfourteen' ),
'id' => 'sidebar-left',
'description' => __( 'Left sidebar.', 'twentyfourteen' ),
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h1 class="widget-title">',
'after_title' => '</h1>',
) );
}
add_action( 'widgets_init', 'mychild_widgets_init' );
</code></pre>
<p>I am also trying this:</p>
<pre><code>'before_wdiget' => '<div id="content">'
'after_widget' => '</div>
</code></pre>
<p>Nothing is working so far.</p>
<p>The sidebar.php file is this:</p>
<pre><code><div id="left">
<?php if ( is_active_sidebar( 'sidebar-left' ) ) : ?>
<div id="left-sidebar" class="left-sidebar widget-area" role="complementary">
<?php dynamic_sidebar( 'sidebar-left' ); ?>
</div>
<?php endif; ?>
</div>
</code></pre>
|
[
{
"answer_id": 199513,
"author": "Eric Holmes",
"author_id": 23454,
"author_profile": "https://wordpress.stackexchange.com/users/23454",
"pm_score": 1,
"selected": false,
"text": "<p><code>get_sidebar('left');</code> actually refers to a file, not the sidebar itself.</p>\n\n<ol>\n<li>Are you seeing the sidebar in the Admin section?</li>\n<li>Are you trying to display it on the front end?</li>\n</ol>\n\n<p>If the answer to both of these questions are \"yes\", then here's the solution:</p>\n\n<p>Create a file called <code>sidebar-left.php</code>. In this file, you will need to add your rendered HTML, something like this:</p>\n\n<pre><code><?php\n// Left Sidebar template\n?>\n<div id=\"left-sidebar\" class=\"sidebar\">\n <?php dynamic_sidebar( 'sidebar-left' ); ?>\n</div>\n</code></pre>\n"
},
{
"answer_id": 199514,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 0,
"selected": false,
"text": "<p>You are mixing up a couple of things here, namely</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow noreferrer\"><code>register_sidebar()</code></a></p>\n\n<p>This is to register a sidebar so you can put stuff into it in the backend.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_sidebar\" rel=\"nofollow noreferrer\"><code>get_sidebar()</code></a></p>\n\n<p>This just includes a file <code>sidebar.php</code> (or <code>sidebar-nice-bar.php</code> if you call <code>get_sidebar('nice-bar')</code>) from your current theme</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/dynamic_sidebar\" rel=\"nofollow noreferrer\"><code>dynamic_sidebar()</code></a></p>\n\n<p>This actually displays the widgets you have added in the backend to the sidebar area defined with <code>register_sidebar</code>. This is probably done in one of the files referenced in <code>get_sidebar</code>.</p>\n\n<p>So what you need to do based on your question is either replacing </p>\n\n<pre><code>get_sidebar('left');\n</code></pre>\n\n<p>with </p>\n\n<pre><code>dynamic_sidebar('left');\n</code></pre>\n\n<p>or create a file called <code>sidebar-left.php</code> in your theme and add <code>dynamic_sidebar('left')</code> to it.</p>\n\n<p>For a more detailed, excellent explanation have a look at <a href=\"http://justintadlock.com/archives/2010/11/08/sidebars-in-wordpress\" rel=\"nofollow noreferrer\">this excellent post</a> by <a href=\"https://wordpress.stackexchange.com/users/41192/justin-tadlock\">@justin-tadlock</a></p>\n"
}
] |
2015/08/24
|
[
"https://wordpress.stackexchange.com/questions/199496",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78091/"
] |
I want an extra sidebar added to this wordpress theme of mine. I want it right under my left sidebar and not next to it as it is currently showing: [www.giftforgag.com](http://www.giftforgag.com).
I have tried many things but nothing seems to be working. I have also tried making various changes to the css.
I had thought it would be easiest to simply place `get_sidebar('left');` right under the `get_sidebar();` function that exists at the very end but it hasn't worked out.
The theme in question is twenty-fourteen and I have placed the code of the file here:
```
<?php
get_header(); ?>
<div id="main-content" class="main-content">
<?php
if ( is_front_page() && twentyfourteen_has_featured_posts() ) {
get_template_part( 'featured-content' );
}
?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile;
twentyfourteen_paging_nav();
else :
get_template_part( 'content', 'none' );
endif;
?>
</div><!-- #content -->
</div><!-- #primary -->
</div><!-- #main-content -->
<?php
get_sidebar();
get_sidebar('left');
get_footer();
```
I have registered the widget using the following code:
```
function mychild_widgets_init() {
register_sidebar( array(
'name' => __( 'Left Widget Area', 'twentyfourteen' ),
'id' => 'sidebar-left',
'description' => __( 'Left sidebar.', 'twentyfourteen' ),
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h1 class="widget-title">',
'after_title' => '</h1>',
) );
}
add_action( 'widgets_init', 'mychild_widgets_init' );
```
I am also trying this:
```
'before_wdiget' => '<div id="content">'
'after_widget' => '</div>
```
Nothing is working so far.
The sidebar.php file is this:
```
<div id="left">
<?php if ( is_active_sidebar( 'sidebar-left' ) ) : ?>
<div id="left-sidebar" class="left-sidebar widget-area" role="complementary">
<?php dynamic_sidebar( 'sidebar-left' ); ?>
</div>
<?php endif; ?>
</div>
```
|
`get_sidebar('left');` actually refers to a file, not the sidebar itself.
1. Are you seeing the sidebar in the Admin section?
2. Are you trying to display it on the front end?
If the answer to both of these questions are "yes", then here's the solution:
Create a file called `sidebar-left.php`. In this file, you will need to add your rendered HTML, something like this:
```
<?php
// Left Sidebar template
?>
<div id="left-sidebar" class="sidebar">
<?php dynamic_sidebar( 'sidebar-left' ); ?>
</div>
```
|
199,498 |
<p>I'm trying to insert data from a wordpress post into a new table database table rather than <code>WP_postmeta</code>. My function is working, It'll insert the <code>$postid</code> no problem at all. The issues I'm having is I need to inser the latitude and longitude coordinates from Marty Spellerbergs 'Address Geocoder' Plugin.</p>
<p>On the plugin page, Marty says you can access the cooridnates inside the loop using these:</p>
<pre><code><?php echo get_geocode_lng( $post->ID ); ?>
<?php echo get_geocode_lat( $post->ID ); ?>
</code></pre>
<p>Now I know being inside the functions.php file, we are not actually inside the lood, so I've tried lots of different ways of accessing this data but I just can't do it. Is there a way to edit those lines specified by Marty so they can be called in the functions?.</p>
<p>This is one of my many many attempts at this:</p>
<pre><code>function save_lat_lng( $post_id )
{
global $wpdb;
global $post;
$custom_lat = $_POST[get_geocode_lat( $post->ID )];
$custom_lng = $_POST[get_geocode_lng( $post->ID )];
// Check that we are editing the right post type
if ( 'festival-event' != $_POST['post_type'] )
{
return;
}
// Check if we have a lat/lng stored for this property already
$check_link = $wpdb->get_row("SELECT * FROM lat_lng_post WHERE post_id = '" . $post_id . "'");
if ($check_link != null)
{
// We already have a lat lng for this post. Update row
$wpdb->update(
'lat_lng_post',
array(
"lat" => $custom_lat,
"lng" => $custom_lng
),
array( 'post_id' => $post_id ),
array(
'%f',
'%f'
)
);
}
else
{
// We do not already have a lat lng for this post. Insert row
$wpdb->insert(
'lat_lng_post',
array(
'post_id' => $post_id,
"lat" => $custom_lat,
"lng" => $custom_lng
),
array(
'%d',
'%f',
'%f'
)
);
}
}
add_action( 'save_post', 'save_lat_lng' )
</code></pre>
|
[
{
"answer_id": 199503,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": true,
"text": "<p>Your syntax is slightly off in a few places. I'll try and let the code explain:</p>\n\n<pre><code>function wpse_199498_meta_to_table( $post_id, $post ) {\n // Use the second argument of our hook, which is the post object\n if ( $post->post_type !== 'festival-event' )\n return;\n\n global $wpdb;\n\n // Don't need to use $_POST, just use the functions as documented\n $custom_lat = get_geocode_lat( $post_id );\n $custom_lng = get_geocode_lng( $post_id );\n\n $check_link = $wpdb->get_var(\n $wpdb->prepare(\n \"SELECT post_id FROM lat_lng_post WHERE post_id = %d\", // Here's that missing comma!\n $post_id\n )\n );\n\n if ( $check_link ) {\n $wpdb->update(\n 'lang_lng_post',\n array( \n 'lat' => $custom_lat,\n 'lng' => $custom_lng,\n ), \n array(\n 'post_id' => $post_id,\n ), \n array( \n '%f', \n '%f',\n ),\n '%d'\n );\n } else {\n $wpdb->insert(\n 'lang_lng_post',\n array( \n 'post_id' => $post_id,\n 'lat' => $custom_lat,\n 'lng' => $custom_lng,\n ), \n array( \n '%d',\n '%f', \n '%f',\n )\n );\n }\n}\n\nadd_action(\n 'wp_insert_post', // Later than \"save_post\", will ensure plugin has already saved meta at this point\n 'wpse_199498_meta_to_table',\n 10, // Default priority\n 2 // Number of arguments\n);\n</code></pre>\n"
},
{
"answer_id": 199508,
"author": "Addzy",
"author_id": 77395,
"author_profile": "https://wordpress.stackexchange.com/users/77395",
"pm_score": 0,
"selected": false,
"text": "<p>This answer was given me to elsewhere, however thought i'd share just in case anyone has similar issues:</p>\n\n<pre><code>function save_lat_lng( $post_id ) \n{ \n global $wpdb; \n\n\nglobal $post;\n$custom_lat = get_geocode_lat( $post_id ); \n$custom_lng = get_geocode_lng( $post_id );\n// Check that we are editing the right post type \nif ( 'festival-event' != $_POST['post_type'] ) \n{ \n return; \n} \n\n\n// Check if we have a lat/lng stored for this property already \n$check_link = $wpdb->get_row(\"SELECT * FROM lat_lng_post WHERE post_id = '\" . $post_id . \"'\"); \nif ($check_link != null) \n{ \n // We already have a lat lng for this post. Update row \n $wpdb->update( \n 'lat_lng_post', \n array( \n \"lat\" => $custom_lat,\n \"lng\" => $custom_lng \n ), \n array( 'post_id' => $post_id ), \n array( \n '%f', \n '%f' \n ) \n ); \n} \nelse \n{ \n // We do not already have a lat lng for this post. Insert row \n $wpdb->insert( \n 'lat_lng_post', \n array( \n 'post_id' => $post_id, \n \"lat\" => $custom_lat,\n \"lng\" => $custom_lng \n ), \n array( \n '%d', \n '%f', \n '%f' \n ) \n ); \n} \n} \nadd_action( 'save_post', 'save_lat_lng', 100 );\n</code></pre>\n\n<p>Also a massive thank you to @TheDeadMedic for spending so much time trying to help me.</p>\n"
}
] |
2015/08/24
|
[
"https://wordpress.stackexchange.com/questions/199498",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77395/"
] |
I'm trying to insert data from a wordpress post into a new table database table rather than `WP_postmeta`. My function is working, It'll insert the `$postid` no problem at all. The issues I'm having is I need to inser the latitude and longitude coordinates from Marty Spellerbergs 'Address Geocoder' Plugin.
On the plugin page, Marty says you can access the cooridnates inside the loop using these:
```
<?php echo get_geocode_lng( $post->ID ); ?>
<?php echo get_geocode_lat( $post->ID ); ?>
```
Now I know being inside the functions.php file, we are not actually inside the lood, so I've tried lots of different ways of accessing this data but I just can't do it. Is there a way to edit those lines specified by Marty so they can be called in the functions?.
This is one of my many many attempts at this:
```
function save_lat_lng( $post_id )
{
global $wpdb;
global $post;
$custom_lat = $_POST[get_geocode_lat( $post->ID )];
$custom_lng = $_POST[get_geocode_lng( $post->ID )];
// Check that we are editing the right post type
if ( 'festival-event' != $_POST['post_type'] )
{
return;
}
// Check if we have a lat/lng stored for this property already
$check_link = $wpdb->get_row("SELECT * FROM lat_lng_post WHERE post_id = '" . $post_id . "'");
if ($check_link != null)
{
// We already have a lat lng for this post. Update row
$wpdb->update(
'lat_lng_post',
array(
"lat" => $custom_lat,
"lng" => $custom_lng
),
array( 'post_id' => $post_id ),
array(
'%f',
'%f'
)
);
}
else
{
// We do not already have a lat lng for this post. Insert row
$wpdb->insert(
'lat_lng_post',
array(
'post_id' => $post_id,
"lat" => $custom_lat,
"lng" => $custom_lng
),
array(
'%d',
'%f',
'%f'
)
);
}
}
add_action( 'save_post', 'save_lat_lng' )
```
|
Your syntax is slightly off in a few places. I'll try and let the code explain:
```
function wpse_199498_meta_to_table( $post_id, $post ) {
// Use the second argument of our hook, which is the post object
if ( $post->post_type !== 'festival-event' )
return;
global $wpdb;
// Don't need to use $_POST, just use the functions as documented
$custom_lat = get_geocode_lat( $post_id );
$custom_lng = get_geocode_lng( $post_id );
$check_link = $wpdb->get_var(
$wpdb->prepare(
"SELECT post_id FROM lat_lng_post WHERE post_id = %d", // Here's that missing comma!
$post_id
)
);
if ( $check_link ) {
$wpdb->update(
'lang_lng_post',
array(
'lat' => $custom_lat,
'lng' => $custom_lng,
),
array(
'post_id' => $post_id,
),
array(
'%f',
'%f',
),
'%d'
);
} else {
$wpdb->insert(
'lang_lng_post',
array(
'post_id' => $post_id,
'lat' => $custom_lat,
'lng' => $custom_lng,
),
array(
'%d',
'%f',
'%f',
)
);
}
}
add_action(
'wp_insert_post', // Later than "save_post", will ensure plugin has already saved meta at this point
'wpse_199498_meta_to_table',
10, // Default priority
2 // Number of arguments
);
```
|
199,521 |
<p>I'm trying to get my posts to order by radius, and so far i'm struggling, I've been using the following tut by Steve MArks, <a href="http://biostall.com/performing-a-radial-search-with-wp_query-in-wordpress" rel="nofollow">http://biostall.com/performing-a-radial-search-with-wp_query-in-wordpress</a></p>
<p>Here's the code that produces the error the following error.</p>
<pre><code>function location_posts_where( $where )
{
global $wpdb;
// Specify the co-ordinates that will form
// the centre of our search
$lat = '50.12335';
$lng = '-1.344453';
$radius = 10; // (in miles)
// Append our radius calculation to the WHERE
$where .= " AND $wpdb->posts.ID IN (SELECT post_id FROM lat_lng_post WHERE
( 3959 * acos( cos( radians(" . $lat . ") )
* cos( radians( lat ) )
* cos( radians( lng )
- radians(" . $lng . ") )
+ sin( radians(" . $lat . ") )
* sin( radians( lat ) ) ) ) <= " . $radius . ")";
// Return the updated WHERE part of the query
return $where;
}
</code></pre>
<p>The error that is chucked up in the debug log is: </p>
<pre><code>WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IN (SELECT `post_id` FROM `lat_lng_post` WHERE ( 3959 * acos( cos( rad' at line 1]
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'festival-event' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND .ID IN (SELECT `post_id` FROM `lat_lng_post` WHERE ( 3959 * acos( cos( radians(50.12335) ) * cos( radians( 'lat' ) ) * cos( radians( 'lng' ) - radians(-1.344453) ) + sin( radians(50.12335) ) * sin( radians( 'lat' ) ) ) ) <= 10) ORDER BY wp_posts.post_date DESC LIMIT 0, 10
</code></pre>
<p>Seems to me that it fails to connect to the database.</p>
<p>I've tried backticking db parts of the string like previous threads say to, but that doesn't work either. </p>
<p>My knowledge of SQL isn't high but it is on my to do list, any help would be really appreciated.</p>
|
[
{
"answer_id": 199503,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": true,
"text": "<p>Your syntax is slightly off in a few places. I'll try and let the code explain:</p>\n\n<pre><code>function wpse_199498_meta_to_table( $post_id, $post ) {\n // Use the second argument of our hook, which is the post object\n if ( $post->post_type !== 'festival-event' )\n return;\n\n global $wpdb;\n\n // Don't need to use $_POST, just use the functions as documented\n $custom_lat = get_geocode_lat( $post_id );\n $custom_lng = get_geocode_lng( $post_id );\n\n $check_link = $wpdb->get_var(\n $wpdb->prepare(\n \"SELECT post_id FROM lat_lng_post WHERE post_id = %d\", // Here's that missing comma!\n $post_id\n )\n );\n\n if ( $check_link ) {\n $wpdb->update(\n 'lang_lng_post',\n array( \n 'lat' => $custom_lat,\n 'lng' => $custom_lng,\n ), \n array(\n 'post_id' => $post_id,\n ), \n array( \n '%f', \n '%f',\n ),\n '%d'\n );\n } else {\n $wpdb->insert(\n 'lang_lng_post',\n array( \n 'post_id' => $post_id,\n 'lat' => $custom_lat,\n 'lng' => $custom_lng,\n ), \n array( \n '%d',\n '%f', \n '%f',\n )\n );\n }\n}\n\nadd_action(\n 'wp_insert_post', // Later than \"save_post\", will ensure plugin has already saved meta at this point\n 'wpse_199498_meta_to_table',\n 10, // Default priority\n 2 // Number of arguments\n);\n</code></pre>\n"
},
{
"answer_id": 199508,
"author": "Addzy",
"author_id": 77395,
"author_profile": "https://wordpress.stackexchange.com/users/77395",
"pm_score": 0,
"selected": false,
"text": "<p>This answer was given me to elsewhere, however thought i'd share just in case anyone has similar issues:</p>\n\n<pre><code>function save_lat_lng( $post_id ) \n{ \n global $wpdb; \n\n\nglobal $post;\n$custom_lat = get_geocode_lat( $post_id ); \n$custom_lng = get_geocode_lng( $post_id );\n// Check that we are editing the right post type \nif ( 'festival-event' != $_POST['post_type'] ) \n{ \n return; \n} \n\n\n// Check if we have a lat/lng stored for this property already \n$check_link = $wpdb->get_row(\"SELECT * FROM lat_lng_post WHERE post_id = '\" . $post_id . \"'\"); \nif ($check_link != null) \n{ \n // We already have a lat lng for this post. Update row \n $wpdb->update( \n 'lat_lng_post', \n array( \n \"lat\" => $custom_lat,\n \"lng\" => $custom_lng \n ), \n array( 'post_id' => $post_id ), \n array( \n '%f', \n '%f' \n ) \n ); \n} \nelse \n{ \n // We do not already have a lat lng for this post. Insert row \n $wpdb->insert( \n 'lat_lng_post', \n array( \n 'post_id' => $post_id, \n \"lat\" => $custom_lat,\n \"lng\" => $custom_lng \n ), \n array( \n '%d', \n '%f', \n '%f' \n ) \n ); \n} \n} \nadd_action( 'save_post', 'save_lat_lng', 100 );\n</code></pre>\n\n<p>Also a massive thank you to @TheDeadMedic for spending so much time trying to help me.</p>\n"
}
] |
2015/08/24
|
[
"https://wordpress.stackexchange.com/questions/199521",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77395/"
] |
I'm trying to get my posts to order by radius, and so far i'm struggling, I've been using the following tut by Steve MArks, <http://biostall.com/performing-a-radial-search-with-wp_query-in-wordpress>
Here's the code that produces the error the following error.
```
function location_posts_where( $where )
{
global $wpdb;
// Specify the co-ordinates that will form
// the centre of our search
$lat = '50.12335';
$lng = '-1.344453';
$radius = 10; // (in miles)
// Append our radius calculation to the WHERE
$where .= " AND $wpdb->posts.ID IN (SELECT post_id FROM lat_lng_post WHERE
( 3959 * acos( cos( radians(" . $lat . ") )
* cos( radians( lat ) )
* cos( radians( lng )
- radians(" . $lng . ") )
+ sin( radians(" . $lat . ") )
* sin( radians( lat ) ) ) ) <= " . $radius . ")";
// Return the updated WHERE part of the query
return $where;
}
```
The error that is chucked up in the debug log is:
```
WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IN (SELECT `post_id` FROM `lat_lng_post` WHERE ( 3959 * acos( cos( rad' at line 1]
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'festival-event' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND .ID IN (SELECT `post_id` FROM `lat_lng_post` WHERE ( 3959 * acos( cos( radians(50.12335) ) * cos( radians( 'lat' ) ) * cos( radians( 'lng' ) - radians(-1.344453) ) + sin( radians(50.12335) ) * sin( radians( 'lat' ) ) ) ) <= 10) ORDER BY wp_posts.post_date DESC LIMIT 0, 10
```
Seems to me that it fails to connect to the database.
I've tried backticking db parts of the string like previous threads say to, but that doesn't work either.
My knowledge of SQL isn't high but it is on my to do list, any help would be really appreciated.
|
Your syntax is slightly off in a few places. I'll try and let the code explain:
```
function wpse_199498_meta_to_table( $post_id, $post ) {
// Use the second argument of our hook, which is the post object
if ( $post->post_type !== 'festival-event' )
return;
global $wpdb;
// Don't need to use $_POST, just use the functions as documented
$custom_lat = get_geocode_lat( $post_id );
$custom_lng = get_geocode_lng( $post_id );
$check_link = $wpdb->get_var(
$wpdb->prepare(
"SELECT post_id FROM lat_lng_post WHERE post_id = %d", // Here's that missing comma!
$post_id
)
);
if ( $check_link ) {
$wpdb->update(
'lang_lng_post',
array(
'lat' => $custom_lat,
'lng' => $custom_lng,
),
array(
'post_id' => $post_id,
),
array(
'%f',
'%f',
),
'%d'
);
} else {
$wpdb->insert(
'lang_lng_post',
array(
'post_id' => $post_id,
'lat' => $custom_lat,
'lng' => $custom_lng,
),
array(
'%d',
'%f',
'%f',
)
);
}
}
add_action(
'wp_insert_post', // Later than "save_post", will ensure plugin has already saved meta at this point
'wpse_199498_meta_to_table',
10, // Default priority
2 // Number of arguments
);
```
|
199,539 |
<p>On a specific page, I would like the search to be performed only against the terms from two custom taxonomies. Not the content or title. That is, the user is directly searching taxonomy terms.</p>
<p>What I'm trying to do is completely rewrite the query for searches, but it doesn't seem to work.</p>
<pre><code>function search_filter_get_posts($query) {
if ( !$query->is_search )
return $query;
$terms = explode(",", $query->query['s']);
$taxquery = array(
'post_type' => 'eproduct',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'product-type',
'field' => 'slug',
'terms' => $terms,
),
array(
'taxonomy' => 'product-features',
'field' => 'slug',
'terms' => $terms,
),
),
);
;
$query = new WP_Query( $taxquery );
}
add_action( 'pre_get_posts', 'search_filter_get_posts' );
</code></pre>
|
[
{
"answer_id": 199571,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 0,
"selected": false,
"text": "<p>I think, the problem is that you just put filtered query in <code>$query</code> variable but did not set it in the main query i.e. <code>$query->set()</code></p>\n\n<p>See if this works in your code -</p>\n\n<p><code>$query->set( 'tax_query', $taxquery );</code></p>\n\n<p>instead of</p>\n\n<p><code>$query = new WP_Query( $taxquery );</code></p>\n"
},
{
"answer_id": 213258,
"author": "user86037",
"author_id": 86037,
"author_profile": "https://wordpress.stackexchange.com/users/86037",
"pm_score": 1,
"selected": false,
"text": "<p>You did not return the new <code>$query</code>; that's why it's not working for you.</p>\n\n<pre><code>$query = new WP_Query( $taxquery ); \nreturn $query;\n</code></pre>\n"
}
] |
2015/08/24
|
[
"https://wordpress.stackexchange.com/questions/199539",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4258/"
] |
On a specific page, I would like the search to be performed only against the terms from two custom taxonomies. Not the content or title. That is, the user is directly searching taxonomy terms.
What I'm trying to do is completely rewrite the query for searches, but it doesn't seem to work.
```
function search_filter_get_posts($query) {
if ( !$query->is_search )
return $query;
$terms = explode(",", $query->query['s']);
$taxquery = array(
'post_type' => 'eproduct',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'product-type',
'field' => 'slug',
'terms' => $terms,
),
array(
'taxonomy' => 'product-features',
'field' => 'slug',
'terms' => $terms,
),
),
);
;
$query = new WP_Query( $taxquery );
}
add_action( 'pre_get_posts', 'search_filter_get_posts' );
```
|
You did not return the new `$query`; that's why it's not working for you.
```
$query = new WP_Query( $taxquery );
return $query;
```
|
199,541 |
<p>I'm trying to make a shortcut in navigation that will take user to one certain post.
So far I'm using </p>
<pre><code>add_action('admin_menu', 'add_custom_menu_position');
function add_custom_menu_position() {
add_menu_page('FeaturedJobs', 'Featured Jobs', 'edit_posts', 'edit.php?post=706&action=edit',18);
}
</code></pre>
<p>The item does show up in the admin menu, but every time I try to use it, it inserts admin? as a part of the link and I get <em>You do not have sufficient permissions to access this page.</em> error. </p>
<p>The final link looks like this: <a href="http://website_url/wp-admin/admin.php?page=post.php?post=706&action=edit" rel="nofollow">http://website_url/wp-admin/admin.php?page=post.php?post=706&action=edit</a></p>
<p>I know that I have enough capabilities to edit it, because I'm on an admin account and also once I use a regular edit link (<a href="http://website_url/wp-admin/post.php?post=706&action=edit" rel="nofollow">http://website_url/wp-admin/post.php?post=706&action=edit</a>), it works fine. I'm rather sure the problem is there because the link I'm trying to reach is wrong, but I can't find a way to link to it in any other way.</p>
<p>I'll be grateful for any hints,
E. </p>
|
[
{
"answer_id": 199571,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 0,
"selected": false,
"text": "<p>I think, the problem is that you just put filtered query in <code>$query</code> variable but did not set it in the main query i.e. <code>$query->set()</code></p>\n\n<p>See if this works in your code -</p>\n\n<p><code>$query->set( 'tax_query', $taxquery );</code></p>\n\n<p>instead of</p>\n\n<p><code>$query = new WP_Query( $taxquery );</code></p>\n"
},
{
"answer_id": 213258,
"author": "user86037",
"author_id": 86037,
"author_profile": "https://wordpress.stackexchange.com/users/86037",
"pm_score": 1,
"selected": false,
"text": "<p>You did not return the new <code>$query</code>; that's why it's not working for you.</p>\n\n<pre><code>$query = new WP_Query( $taxquery ); \nreturn $query;\n</code></pre>\n"
}
] |
2015/08/24
|
[
"https://wordpress.stackexchange.com/questions/199541",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33202/"
] |
I'm trying to make a shortcut in navigation that will take user to one certain post.
So far I'm using
```
add_action('admin_menu', 'add_custom_menu_position');
function add_custom_menu_position() {
add_menu_page('FeaturedJobs', 'Featured Jobs', 'edit_posts', 'edit.php?post=706&action=edit',18);
}
```
The item does show up in the admin menu, but every time I try to use it, it inserts admin? as a part of the link and I get *You do not have sufficient permissions to access this page.* error.
The final link looks like this: <http://website_url/wp-admin/admin.php?page=post.php?post=706&action=edit>
I know that I have enough capabilities to edit it, because I'm on an admin account and also once I use a regular edit link (<http://website_url/wp-admin/post.php?post=706&action=edit>), it works fine. I'm rather sure the problem is there because the link I'm trying to reach is wrong, but I can't find a way to link to it in any other way.
I'll be grateful for any hints,
E.
|
You did not return the new `$query`; that's why it's not working for you.
```
$query = new WP_Query( $taxquery );
return $query;
```
|
199,603 |
<p>I'm looking to disable the 'media file' image link on mobile devices, so that when viewing a site on mobile devices we simply have the image being displayed with no link to anything.</p>
<p>I am looking to achieve this because in a responsive design my images are at 100% width on mobile devices anyway. Clicking on the image simply opens an image that is the same size, or even smaller depending on the lightbox padding settings.</p>
<p>I use the <a href="https://wordpress.org/plugins/shadowbox-js/" rel="nofollow noreferrer">shadowbox js plugin</a> to open media file image links in a responsive lightbox. This plugin detects a media file image link and adds a rel="shadowbox" to open up the full size version in a lightbox.</p>
<p>I'm beginning here by trying to implement the described functionality within the native WordPress media file image link code, as I believe the plugin simply hooks into that.</p>
<p>I've researched this quite a bit, to no avail. One unsuccessful implementation I've attempted was from the following thread - <a href="https://wordpress.stackexchange.com/questions/104957/disable-linked-gallery-images-if-mobile-browser">Disable Linked Gallery Images If Mobile Browser</a></p>
<p>In doing so I added the following code to my functions.php file (I'd like to achieve this either via my functions.php file or a plugin), but it didn't work.</p>
<pre><code>$image = wp_get_attachment_image( $id, $size, false );
// if it's set to not show the image link
if(isset($attr['link']) && ('none' == $attr['link']) && !is_mobile() ){
// then just show the image
echo $image;
} else {
// else show the image wrapped in a link
$link = wp_get_attachment_url($id);
echo "<a href=\"$link\">$image</a>";
}
</code></pre>
<p>Is it possible to disable the 'media file' image link on mobile devices?</p>
|
[
{
"answer_id": 199606,
"author": "David Gallagher",
"author_id": 78289,
"author_profile": "https://wordpress.stackexchange.com/users/78289",
"pm_score": 0,
"selected": false,
"text": "<p>What you want to do isn't possible from <code>functions.php</code> or a plugin. The code you have posted would need to replace code in your template files for the page displaying your images.</p>\n\n<p>If you can modify the template files, find where in your template generates your image HTML and then you can replace it with something similar to the code you have posted. It's very likely that you will need to modify the code you posted above in some way.</p>\n\n<p>Also, unless you have added the <code>is_mobile()</code> function, you will need to replace <code>is_mobile()</code> with <code>wp_is_mobile()</code>.</p>\n\n<p>Finally I should add that this isn't a \"responsive\" solution. Ideally you should use HTML and/or CSS and/or JavaScript to solve your issue.</p>\n"
},
{
"answer_id": 244956,
"author": "Sandeep",
"author_id": 106236,
"author_profile": "https://wordpress.stackexchange.com/users/106236",
"pm_score": 1,
"selected": false,
"text": "<p>You can easily do this using HTML and CSS. You can write 2 blocks of div for the same image and toogle display:none; properties in CSS using media queries as shown below. Note: I have remove the \"a href\" tag for mobile.</p>\n\n<pre><code><!--HTML Start -->\n <div class=\"image-grid desktop\">\n <a href=\"#\"><img src=\"#\" /></a>\n <div>\n\n <!--For Mobile -->\n\n <div class=\"image-grid mobile\">\n <img src=\"#\" />\n <div>\n\n<!--HTML End -->\n\n<!--CSS Start -->\n.image-grid.mobile{display:none;}\n\n\n@media only screen \n and (min-device-width: 320px) \n and (max-device-width: 480px)\n and (-webkit-min-device-pixel-ratio: 1) {\n\n.image-grid.desktop{display:none;}\n.image-grid.mobile{display:block;}\n\n}\n\n\n<!--CSS End -->\n</code></pre>\n"
}
] |
2015/08/25
|
[
"https://wordpress.stackexchange.com/questions/199603",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78294/"
] |
I'm looking to disable the 'media file' image link on mobile devices, so that when viewing a site on mobile devices we simply have the image being displayed with no link to anything.
I am looking to achieve this because in a responsive design my images are at 100% width on mobile devices anyway. Clicking on the image simply opens an image that is the same size, or even smaller depending on the lightbox padding settings.
I use the [shadowbox js plugin](https://wordpress.org/plugins/shadowbox-js/) to open media file image links in a responsive lightbox. This plugin detects a media file image link and adds a rel="shadowbox" to open up the full size version in a lightbox.
I'm beginning here by trying to implement the described functionality within the native WordPress media file image link code, as I believe the plugin simply hooks into that.
I've researched this quite a bit, to no avail. One unsuccessful implementation I've attempted was from the following thread - [Disable Linked Gallery Images If Mobile Browser](https://wordpress.stackexchange.com/questions/104957/disable-linked-gallery-images-if-mobile-browser)
In doing so I added the following code to my functions.php file (I'd like to achieve this either via my functions.php file or a plugin), but it didn't work.
```
$image = wp_get_attachment_image( $id, $size, false );
// if it's set to not show the image link
if(isset($attr['link']) && ('none' == $attr['link']) && !is_mobile() ){
// then just show the image
echo $image;
} else {
// else show the image wrapped in a link
$link = wp_get_attachment_url($id);
echo "<a href=\"$link\">$image</a>";
}
```
Is it possible to disable the 'media file' image link on mobile devices?
|
You can easily do this using HTML and CSS. You can write 2 blocks of div for the same image and toogle display:none; properties in CSS using media queries as shown below. Note: I have remove the "a href" tag for mobile.
```
<!--HTML Start -->
<div class="image-grid desktop">
<a href="#"><img src="#" /></a>
<div>
<!--For Mobile -->
<div class="image-grid mobile">
<img src="#" />
<div>
<!--HTML End -->
<!--CSS Start -->
.image-grid.mobile{display:none;}
@media only screen
and (min-device-width: 320px)
and (max-device-width: 480px)
and (-webkit-min-device-pixel-ratio: 1) {
.image-grid.desktop{display:none;}
.image-grid.mobile{display:block;}
}
<!--CSS End -->
```
|
199,608 |
<p>Many people has asked the same question, I have read those things and mine is different,</p>
<p>I am trying to insert some values inside the database from the form but it's not getting inserted</p>
<p>I have a table in the database having 6 columns wanted to insert some values inside only of 4 columns</p>
<p>Table Name: <code>wp_contactus</code></p>
<ul>
<li><p>6 Columns</p>
<ul>
<li>id</li>
<li>firstname</li>
<li>lastname</li>
<li>email</li>
<li>query</li>
<li>reg_date</li>
</ul></li>
</ul>
<p>This is the code for inserting only in the 4 columns</p>
<ul>
<li><p>4 Columns</p>
<ul>
<li>firstname</li>
<li>secondname</li>
<li>email</li>
<li>query</li>
</ul></li>
</ul>
<p>The code:</p>
<pre><code> <div class="wrap">
<form action="" method="post">
FirstName <input type="text" name="firstNametxt" value="" /><br/>
LastName <input type="text" name="lastNametxt" value="" /><br/>
email <input type="text" name="email" value="" /><br/>
Query <input type="text" name="query" value="" /><br/>
<input name="Submit" type="submit" value="Submit">
</form>
<form method="post">
<?php
global $wpdb;
$firstName = $_POST["firstNametxt"];
$lastName = $_POST["lastNametxt"];
$email = $_POST["email"];
$query = $_POST["query"];
echo $firstName;
$contactus_table = $wpdb->prefix."contactus";
$sql = "INSERT INTO $contactus_table (id, firstname, lastname, email,
query, reg_date) VALUES ('2', $firstName, $lastName, $email, $query,
CURRENT_TIMESTAMP);";
$wpdb->query($sql))
?>
</form>
</div>
<?php
}
add_shortcode( 'CONUS', 'contactus_shortcode' );
?>
<?php
}
add_shortcode( 'CONUS', 'contactus_shortcode' );
?>
</code></pre>
|
[
{
"answer_id": 199614,
"author": "Mat",
"author_id": 10914,
"author_profile": "https://wordpress.stackexchange.com/users/10914",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like you are trying to insert the data before the form is submitted. Your code above had two forms, one for input and one with PHP.</p>\n\n<p>You need to check whether the form has been submitted then action the PHP code or if not display the form.</p>\n\n<pre><code>$submitted_form = $_POST['submit'];\n\nif(isset($submitted_form)) {\n //process and validate, then insert\n} else {\n // nothing submitted, so lets display the form\n <form action=\"\" method=\"post\">\n FirstName <input type=\"text\" name=\"firstNametxt\" value=\"\" /><br/>\n LastName <input type=\"text\" name=\"lastNametxt\" value=\"\" /><br/>\n email <input type=\"text\" name=\"email\" value=\"\" /><br/>\n Query <input type=\"text\" name=\"query\" value=\"\" /><br/>\n <input name=\"Submit\" type=\"submit\" value=\"Submit\">\n </form>\n}\n</code></pre>\n\n<p>this should point you in the right direction.</p>\n"
},
{
"answer_id": 199616,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/zF8QT.jpg\" rel=\"nofollow noreferrer\">You're inserting raw POST data straight into an SQL query</a> - sanitize, sanitize, sanitize! The code below should get you started, but I would advise you add some additional checks (is the email valid? are the strings too long? etc.):</p>\n\n<pre><code><?php\n\n$errors =\n$values = array();\n\nif ( isset( $_POST['Submit'] ) ) {\n $fields = array(\n 'firstNametxt',\n 'lastNametxt',\n 'email',\n 'query',\n );\n\n foreach ( $fields as $field ) {\n if ( isset( $_POST[ $field ] ) ) { // Never assume a POST field will be set\n // Ensure the value is a string, POST data can be an array if the user is meddling\n $value = ( string ) $_POST[ $field ];\n\n // Strip slashes that WordPress adds\n $value = wp_unslash( $value );\n\n // Remove trailing/preceding whitespace\n $value = trim( $value );\n\n // Core WordPress function to check for invalid UTF-8, strip tags, remove line breaks etc.\n $value = sanitize_text_field( $value );\n } else {\n $value = '';\n }\n\n if ( ! $value )\n $errors[ $field ] = 'This field is required.';\n else\n $values[ $field ] = $value;\n }\n\n if ( ! $errors ) {\n $wpdb->insert(\n $wpdb->prefix . 'contactus',\n $values,\n '%s'\n );\n }\n}\n\n?>\n\n<?php if ( $errors ) : ?>\n\n <p>Please ensure all fields are completed.</p>\n\n<?php endif ?>\n\n<form method=\"post\">\n FirstName <input type=\"text\" name=\"firstNametxt\" value=\"\" /><br/>\n LastName <input type=\"text\" name=\"lastNametxt\" value=\"\" /><br/>\n email <input type=\"text\" name=\"email\" value=\"\" /><br/>\n Query <input type=\"text\" name=\"query\" value=\"\" /><br/>\n <input name=\"Submit\" type=\"submit\" value=\"Submit\">\n</form>\n</code></pre>\n\n<p>And <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#INSERT_rows\" rel=\"nofollow noreferrer\">read up on the codex for safely inserting into tables using <code>wpdb::insert()</code></a></p>\n"
}
] |
2015/08/25
|
[
"https://wordpress.stackexchange.com/questions/199608",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78297/"
] |
Many people has asked the same question, I have read those things and mine is different,
I am trying to insert some values inside the database from the form but it's not getting inserted
I have a table in the database having 6 columns wanted to insert some values inside only of 4 columns
Table Name: `wp_contactus`
* 6 Columns
+ id
+ firstname
+ lastname
+ email
+ query
+ reg\_date
This is the code for inserting only in the 4 columns
* 4 Columns
+ firstname
+ secondname
+ email
+ query
The code:
```
<div class="wrap">
<form action="" method="post">
FirstName <input type="text" name="firstNametxt" value="" /><br/>
LastName <input type="text" name="lastNametxt" value="" /><br/>
email <input type="text" name="email" value="" /><br/>
Query <input type="text" name="query" value="" /><br/>
<input name="Submit" type="submit" value="Submit">
</form>
<form method="post">
<?php
global $wpdb;
$firstName = $_POST["firstNametxt"];
$lastName = $_POST["lastNametxt"];
$email = $_POST["email"];
$query = $_POST["query"];
echo $firstName;
$contactus_table = $wpdb->prefix."contactus";
$sql = "INSERT INTO $contactus_table (id, firstname, lastname, email,
query, reg_date) VALUES ('2', $firstName, $lastName, $email, $query,
CURRENT_TIMESTAMP);";
$wpdb->query($sql))
?>
</form>
</div>
<?php
}
add_shortcode( 'CONUS', 'contactus_shortcode' );
?>
<?php
}
add_shortcode( 'CONUS', 'contactus_shortcode' );
?>
```
|
[You're inserting raw POST data straight into an SQL query](https://i.stack.imgur.com/zF8QT.jpg) - sanitize, sanitize, sanitize! The code below should get you started, but I would advise you add some additional checks (is the email valid? are the strings too long? etc.):
```
<?php
$errors =
$values = array();
if ( isset( $_POST['Submit'] ) ) {
$fields = array(
'firstNametxt',
'lastNametxt',
'email',
'query',
);
foreach ( $fields as $field ) {
if ( isset( $_POST[ $field ] ) ) { // Never assume a POST field will be set
// Ensure the value is a string, POST data can be an array if the user is meddling
$value = ( string ) $_POST[ $field ];
// Strip slashes that WordPress adds
$value = wp_unslash( $value );
// Remove trailing/preceding whitespace
$value = trim( $value );
// Core WordPress function to check for invalid UTF-8, strip tags, remove line breaks etc.
$value = sanitize_text_field( $value );
} else {
$value = '';
}
if ( ! $value )
$errors[ $field ] = 'This field is required.';
else
$values[ $field ] = $value;
}
if ( ! $errors ) {
$wpdb->insert(
$wpdb->prefix . 'contactus',
$values,
'%s'
);
}
}
?>
<?php if ( $errors ) : ?>
<p>Please ensure all fields are completed.</p>
<?php endif ?>
<form method="post">
FirstName <input type="text" name="firstNametxt" value="" /><br/>
LastName <input type="text" name="lastNametxt" value="" /><br/>
email <input type="text" name="email" value="" /><br/>
Query <input type="text" name="query" value="" /><br/>
<input name="Submit" type="submit" value="Submit">
</form>
```
And [read up on the codex for safely inserting into tables using `wpdb::insert()`](https://codex.wordpress.org/Class_Reference/wpdb#INSERT_rows)
|
199,668 |
<p>What does it mean when (according to mySQL Workbench) 2 options have option_id = 0?</p>
<p>Just noticed this for unrelated plugin and theme holding very different options.</p>
<p><em>Update</em> Just noticed over 200 options had id 0 (<code>select * from wordpress.wp_options where option_id = 0</code>) on one test system. What causes this, and could this be a reason transients seem to be deleted early?</p>
|
[
{
"answer_id": 212249,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>If we check how the <code>wp_options</code> table is created (in 4.4) from the <code>schema.php</code> file, we will find the following:</p>\n\n<pre><code>CREATE TABLE $wpdb->options (\n option_id bigint(20) unsigned NOT NULL auto_increment,\n option_name varchar(191) NOT NULL default '',\n option_value longtext NOT NULL,\n autoload varchar(20) NOT NULL default 'yes',\n PRIMARY KEY (option_id),\n UNIQUE KEY option_name (option_name)\n) $charset_collate;\n</code></pre>\n\n<p>Here's how this structure looks like for the <code>wp_options</code> table:</p>\n\n<pre><code>> DESCRIBE wp_options;\n+--------------+---------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+---------------------+------+-----+---------+----------------+\n| option_id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |\n| option_name | varchar(191) | NO | UNI | | |\n| option_value | longtext | NO | | NULL | |\n| autoload | varchar(20) | NO | | yes | |\n+--------------+---------------------+------+-----+---------+----------------+\n</code></pre>\n\n<p>If this happened just recently you should check your error logs for PHP, MySQL, NginX/Apache.</p>\n\n<p>Not sure what your MySQL version is, but the <a href=\"https://wordpress.org/about/requirements/\" rel=\"nofollow\">recommended</a> version is 5.6+ but should work on 5.0+.</p>\n\n<p>Make sure the table structure of the other core tables is intact as well.</p>\n\n<p>Remember to <strong>backup</strong> your database before altering the table structure.</p>\n"
},
{
"answer_id": 212384,
"author": "Saikat",
"author_id": 28168,
"author_profile": "https://wordpress.stackexchange.com/users/28168",
"pm_score": 1,
"selected": false,
"text": "<p>I faced same type of issue when I imported my database via phpmyadmin. I think, if you have a database backup, then you can try another re-import operation vaia phpmyadmin. That worked for me, but not sure if that works for you.</p>\n"
},
{
"answer_id": 212422,
"author": "Kvvaradha",
"author_id": 43308,
"author_profile": "https://wordpress.stackexchange.com/users/43308",
"pm_score": 1,
"selected": false,
"text": "<p>If you import the database on your phpmyadmin. It has an option while importing sql files. <code>Don't use AUTO_INCREMENT for null tables or zero rows</code>. This option just above the go button. Read this checkbox and mark it based on your choice. Than import your database. It won't be the problem. The <code>option_ID</code> is an primary key and it's AUTO_INCREMENT.</p>\n\n<p>If you are using phpmyadmin. Go-to the options table and it's structure view. Than make it primary key and edit the field and check the AUTO_INCREMENT in it. Than your prblem will be solved. </p>\n"
}
] |
2015/08/25
|
[
"https://wordpress.stackexchange.com/questions/199668",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25767/"
] |
What does it mean when (according to mySQL Workbench) 2 options have option\_id = 0?
Just noticed this for unrelated plugin and theme holding very different options.
*Update* Just noticed over 200 options had id 0 (`select * from wordpress.wp_options where option_id = 0`) on one test system. What causes this, and could this be a reason transients seem to be deleted early?
|
If we check how the `wp_options` table is created (in 4.4) from the `schema.php` file, we will find the following:
```
CREATE TABLE $wpdb->options (
option_id bigint(20) unsigned NOT NULL auto_increment,
option_name varchar(191) NOT NULL default '',
option_value longtext NOT NULL,
autoload varchar(20) NOT NULL default 'yes',
PRIMARY KEY (option_id),
UNIQUE KEY option_name (option_name)
) $charset_collate;
```
Here's how this structure looks like for the `wp_options` table:
```
> DESCRIBE wp_options;
+--------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------------+------+-----+---------+----------------+
| option_id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| option_name | varchar(191) | NO | UNI | | |
| option_value | longtext | NO | | NULL | |
| autoload | varchar(20) | NO | | yes | |
+--------------+---------------------+------+-----+---------+----------------+
```
If this happened just recently you should check your error logs for PHP, MySQL, NginX/Apache.
Not sure what your MySQL version is, but the [recommended](https://wordpress.org/about/requirements/) version is 5.6+ but should work on 5.0+.
Make sure the table structure of the other core tables is intact as well.
Remember to **backup** your database before altering the table structure.
|
199,682 |
<p>I am trying to write a get_posts() query to retrieve 7 posts per page. The retrieval of these posts are based on 3 different tags, "Featured","Highlighted", and "News". Now the "Featured" post take priority over all others, so if there are 7 Featured Posts then only those post should be displayed on the page. The "Highlighted" posts are second in line when it comes to order of importance. So if there are 2 "Featured" posts and 5 "highlighted" posts that is what should display. Then finally whatever is left over "News" is the final tag designation as far as displaying posts by order of importance. </p>
<p>Here is what I have so far:</p>
<pre><code>public function automate_posts_to_send(){
$value = get_option( 'email_settings_options');
$article_number = $value['number_of_articles_to_send'];
$posts = get_posts( array(
"tag__in" => array(135, 239, 256),
"orderby" => 'tag__in',
'date_query' => array(
array(
'after' => '24 hours ago'
),
),
"posts_per_page" => $article_number
) );
return $posts;
}
</code></pre>
<p>I am getting the list but the post order is not right. I want the post ordered this way by these tags: Featured, Highlighted, News</p>
|
[
{
"answer_id": 199698,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 0,
"selected": false,
"text": "<p>tag__in is not listed as a valid orderby value in <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow\">the codex</a>.</p>\n\n<p>I'd suggest grabbing more posts than you need, and ordering them within your PHP. </p>\n"
},
{
"answer_id": 199702,
"author": "Manny Fleurmond",
"author_id": 2234,
"author_profile": "https://wordpress.stackexchange.com/users/2234",
"pm_score": 0,
"selected": false,
"text": "<p>By default, WP doesn't sort by taxonomy/tag. A probable solution is doing 3 separate get_posts calls, one for each tag, then using array_merge to combine the results into 1 array.</p>\n"
},
{
"answer_id": 199730,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<p>It is quite easy to achieve this. Your answer is <code>usort()</code></p>\n\n<h2>FEW NOTES:</h2>\n\n<p>Before we code, just a few notes</p>\n\n<ul>\n<li><p>Requires PHP5.4+ due to the use of the short array syntax (<code>[]</code>). If you have an older version, you should really upgrade as older versions are a real security threat as all older versions prior to PHP 5.4 has been EOL'ed</p></li>\n<li><p>I will comment the code as I go along so you can easy follow it</p></li>\n<li><p>Taxonomy terms and custom fields are cached, so you will not be doing extra db calls, so the solution is still very lean. </p></li>\n<li><p>The code below is untested, so be sure to test this locally first</p></li>\n</ul>\n\n<h2>THE CODE:</h2>\n\n<pre><code>public function automate_posts_to_send()\n{\n $value = get_option( 'email_settings_options');\n $article_number = $value['number_of_articles_to_send'];\n\n /**\n * Add the tag ids here in the correct order you need your posts to be in\n * In this example, posts from tag 2 will show first, then posts from tag 3 then tag 1\n * As I said, I'm using short array syntax, so for older versions of PHP prior to 5.4,\n * [2, 3, 1] would become array( 2, 3, 1 )\n */\n $tag_order = [2, 3, 1]; \n $args = [ \n 'tag__in' => $tag_order,\n //'orderby' => $tag_order // This is invalid ordering, add valid value here according to needs\n 'posts_per_page' => $article_number,\n 'date_query' => [\n [\n 'after' => '24 hours ago'\n ]\n ],\n ];\n $posts_array = get_posts( $args );\n\n /**\n * Now we will sort the returned array of posts as we need them according to $tag_order. We will use usort()\n *\n * There is a bug in usort causing the following error:\n * usort(): Array was modified by the user comparison function\n * @see https://bugs.php.net/bug.php?id=50688\n * This bug has yet to be fixed, when, no one knows. The only workaround is to suppress the error reporting\n * by using the @ sign before usort\n */\n @usort( $posts_array, function ( $a, $b ) use ( $tag_order )\n {\n // Store our post ids in an array. We will use that to get our post tags per post\n $array = [\n 'a' => $a->ID, // Use only post ID\n 'b' => $b->ID // Same as above\n ];\n // Define our two variables which will hold the desired tag id\n $array_a = [];\n $array_b = [];\n\n // We will now get and store our post tags according to the tags in $tag_order\n foreach ( $array as $k=>$v ) {\n $tags = get_the_tags( $v );\n if ( $tags ) {\n foreach ( $tags as $tag ) {\n if ( !in_array( $tag->term_id, $tag_order ) )\n continue;\n\n // If we found a tag that is in the $tag_order array, store it and break the foreach loop\n ${'array_' . $k}[] = $tag->term_id; // Will produce $array_a[] = $tag->term_id or $array_b[] = $tag->term_id\n\n // If we found the tag we are looking for, break the foreach loop\n break;\n } // endforeach $tags\n } // endif $tags\n } // endforeach $array\n\n // Flip the $tag_order array for sorting purposes\n $flipped_tag_order = array_flip( $tag_order );\n\n /**\n * Lets sort our array now\n *\n * We will sort according to tag first. If the tags between two posts being compared are the same\n * we will sort the posts by post date. Adjust this as necessary\n */\n if ( $flipped_tag_order[$array_a] != $flipped_tag_order[$array_b] ) {\n return $flipped_tag_order[$array_a] - $flipped_tag_order[$array_b];\n } else {\n return $a->post_date < $b->post_date; // Change to > if you need oldest posts first\n }\n }); // end our usort ordering\n\n // We are done sorting, etc. Return our $posts_array\n return $posts_array;\n}\n</code></pre>\n"
}
] |
2015/08/25
|
[
"https://wordpress.stackexchange.com/questions/199682",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43155/"
] |
I am trying to write a get\_posts() query to retrieve 7 posts per page. The retrieval of these posts are based on 3 different tags, "Featured","Highlighted", and "News". Now the "Featured" post take priority over all others, so if there are 7 Featured Posts then only those post should be displayed on the page. The "Highlighted" posts are second in line when it comes to order of importance. So if there are 2 "Featured" posts and 5 "highlighted" posts that is what should display. Then finally whatever is left over "News" is the final tag designation as far as displaying posts by order of importance.
Here is what I have so far:
```
public function automate_posts_to_send(){
$value = get_option( 'email_settings_options');
$article_number = $value['number_of_articles_to_send'];
$posts = get_posts( array(
"tag__in" => array(135, 239, 256),
"orderby" => 'tag__in',
'date_query' => array(
array(
'after' => '24 hours ago'
),
),
"posts_per_page" => $article_number
) );
return $posts;
}
```
I am getting the list but the post order is not right. I want the post ordered this way by these tags: Featured, Highlighted, News
|
It is quite easy to achieve this. Your answer is `usort()`
FEW NOTES:
----------
Before we code, just a few notes
* Requires PHP5.4+ due to the use of the short array syntax (`[]`). If you have an older version, you should really upgrade as older versions are a real security threat as all older versions prior to PHP 5.4 has been EOL'ed
* I will comment the code as I go along so you can easy follow it
* Taxonomy terms and custom fields are cached, so you will not be doing extra db calls, so the solution is still very lean.
* The code below is untested, so be sure to test this locally first
THE CODE:
---------
```
public function automate_posts_to_send()
{
$value = get_option( 'email_settings_options');
$article_number = $value['number_of_articles_to_send'];
/**
* Add the tag ids here in the correct order you need your posts to be in
* In this example, posts from tag 2 will show first, then posts from tag 3 then tag 1
* As I said, I'm using short array syntax, so for older versions of PHP prior to 5.4,
* [2, 3, 1] would become array( 2, 3, 1 )
*/
$tag_order = [2, 3, 1];
$args = [
'tag__in' => $tag_order,
//'orderby' => $tag_order // This is invalid ordering, add valid value here according to needs
'posts_per_page' => $article_number,
'date_query' => [
[
'after' => '24 hours ago'
]
],
];
$posts_array = get_posts( $args );
/**
* Now we will sort the returned array of posts as we need them according to $tag_order. We will use usort()
*
* There is a bug in usort causing the following error:
* usort(): Array was modified by the user comparison function
* @see https://bugs.php.net/bug.php?id=50688
* This bug has yet to be fixed, when, no one knows. The only workaround is to suppress the error reporting
* by using the @ sign before usort
*/
@usort( $posts_array, function ( $a, $b ) use ( $tag_order )
{
// Store our post ids in an array. We will use that to get our post tags per post
$array = [
'a' => $a->ID, // Use only post ID
'b' => $b->ID // Same as above
];
// Define our two variables which will hold the desired tag id
$array_a = [];
$array_b = [];
// We will now get and store our post tags according to the tags in $tag_order
foreach ( $array as $k=>$v ) {
$tags = get_the_tags( $v );
if ( $tags ) {
foreach ( $tags as $tag ) {
if ( !in_array( $tag->term_id, $tag_order ) )
continue;
// If we found a tag that is in the $tag_order array, store it and break the foreach loop
${'array_' . $k}[] = $tag->term_id; // Will produce $array_a[] = $tag->term_id or $array_b[] = $tag->term_id
// If we found the tag we are looking for, break the foreach loop
break;
} // endforeach $tags
} // endif $tags
} // endforeach $array
// Flip the $tag_order array for sorting purposes
$flipped_tag_order = array_flip( $tag_order );
/**
* Lets sort our array now
*
* We will sort according to tag first. If the tags between two posts being compared are the same
* we will sort the posts by post date. Adjust this as necessary
*/
if ( $flipped_tag_order[$array_a] != $flipped_tag_order[$array_b] ) {
return $flipped_tag_order[$array_a] - $flipped_tag_order[$array_b];
} else {
return $a->post_date < $b->post_date; // Change to > if you need oldest posts first
}
}); // end our usort ordering
// We are done sorting, etc. Return our $posts_array
return $posts_array;
}
```
|
199,694 |
<p>I have a multisite WordPress installation set up, and have a user who is set to an 'Administrator' role on both sites. However, the function <code>current_user_can('Administrator')</code> does not return true when logged in as them, which I expected it to.</p>
<p>My user account, however, is an 'Administrator' on both sites, and <em>also</em> a 'Super Admin' on the network, and the call returns true for me.</p>
<p>Why is this? Shouldn't the first user only be false if checking for 'Super Admin' and not just 'Administrator'?</p>
<p>If this is an issue, is there any other way that I can check if a user is set to the 'Administrator' role without being a 'Super Admin'?</p>
|
[
{
"answer_id": 199696,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 3,
"selected": true,
"text": "<p>I would agree that current_user_can('Administrator') should return true for the user. However, current_user_can is primarily intended to check for capabilities, which is generally a more robust check to be making.</p>\n\n<p>I'd suggest something like this (untested):</p>\n\n<pre><code>if ( current_user_can( 'activate_plugins' ) && ! current_user_can( 'update_core' ) ) {\n//...\n}\n</code></pre>\n\n<p>So this is checking if the current user can activate plugins but cannot update core. This should return true for Administrators whilst returning false for Network Admins - as on multisite update_core is reserved for Network Admins.</p>\n"
},
{
"answer_id": 286853,
"author": "dvp",
"author_id": 132049,
"author_profile": "https://wordpress.stackexchange.com/users/132049",
"pm_score": 3,
"selected": false,
"text": "<p>There is a Typo in your expression use <code>current_user_can('administrator')</code> instead of <code>current_user_can('Administrator')</code> (a instead of A). </p>\n"
}
] |
2015/08/25
|
[
"https://wordpress.stackexchange.com/questions/199694",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78346/"
] |
I have a multisite WordPress installation set up, and have a user who is set to an 'Administrator' role on both sites. However, the function `current_user_can('Administrator')` does not return true when logged in as them, which I expected it to.
My user account, however, is an 'Administrator' on both sites, and *also* a 'Super Admin' on the network, and the call returns true for me.
Why is this? Shouldn't the first user only be false if checking for 'Super Admin' and not just 'Administrator'?
If this is an issue, is there any other way that I can check if a user is set to the 'Administrator' role without being a 'Super Admin'?
|
I would agree that current\_user\_can('Administrator') should return true for the user. However, current\_user\_can is primarily intended to check for capabilities, which is generally a more robust check to be making.
I'd suggest something like this (untested):
```
if ( current_user_can( 'activate_plugins' ) && ! current_user_can( 'update_core' ) ) {
//...
}
```
So this is checking if the current user can activate plugins but cannot update core. This should return true for Administrators whilst returning false for Network Admins - as on multisite update\_core is reserved for Network Admins.
|
199,709 |
<p>I have set some extra profile fields set in buddypress (under users profile fields), and I want to make sure they are read only with the exception of site administrators.</p>
<p>How do I accomplish this?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 199722,
"author": "jim.duck",
"author_id": 78337,
"author_profile": "https://wordpress.stackexchange.com/users/78337",
"pm_score": 0,
"selected": false,
"text": "<p>Add this snippet to your child-theme functions.php or <a href=\"https://codex.buddypress.org/themes/bp-custom-php/\" rel=\"nofollow\">bp-custom.php</a></p>\n\n<pre><code>function bpfr_hide_profile_edit( $retval ) { \n// remove field from edit tab\nif( bp_is_profile_edit() ) { \n $retval['exclude_fields'] = '2'; // field ID's separated by comma\n} \n// allow field on register page\nif ( bp_is_register_page() ) {\n $retval['include_fields'] = '2'; // field ID's separated by comma\n } \n\n// hide the field on profile view tab\nif ( $data = bp_get_profile_field_data( 'field=2' ) ) : \n $retval['exclude_fields'] = '2'; // field ID's separated by comma \nendif; \n\nreturn $retval; \n}\nadd_filter( 'bp_after_has_profile_parse_args', 'bpfr_hide_profile_edit' );\n</code></pre>\n"
},
{
"answer_id": 199827,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 3,
"selected": true,
"text": "<p>You can hide profile fields on the edit screen from everyone except site admins - therefore they can only be edited by site admins. They will still be visible on the public profile screen. You can get the field id by looking at the url in wp-admin when you edit that field, or just rolling over the edit button. Add this function to your child-theme functions.php or <a href=\"https://codex.buddypress.org/themes/bp-custom-php/\" rel=\"nofollow\">bp-custom.php</a></p>\n\n<pre><code>function arcee_hide_profile_fields( $retval ) {\n\n if( is_super_admin () )\n return $retval;\n\n if( bp_is_profile_edit() )\n $retval['exclude_fields'] = '3,43,253'; //field ID's separated by comma\n\n return $retval;\n\n}\nadd_filter( 'bp_after_has_profile_parse_args', 'arcee_hide_profile_fields' );\n</code></pre>\n"
}
] |
2015/08/26
|
[
"https://wordpress.stackexchange.com/questions/199709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68446/"
] |
I have set some extra profile fields set in buddypress (under users profile fields), and I want to make sure they are read only with the exception of site administrators.
How do I accomplish this?
Thank you.
|
You can hide profile fields on the edit screen from everyone except site admins - therefore they can only be edited by site admins. They will still be visible on the public profile screen. You can get the field id by looking at the url in wp-admin when you edit that field, or just rolling over the edit button. Add this function to your child-theme functions.php or [bp-custom.php](https://codex.buddypress.org/themes/bp-custom-php/)
```
function arcee_hide_profile_fields( $retval ) {
if( is_super_admin () )
return $retval;
if( bp_is_profile_edit() )
$retval['exclude_fields'] = '3,43,253'; //field ID's separated by comma
return $retval;
}
add_filter( 'bp_after_has_profile_parse_args', 'arcee_hide_profile_fields' );
```
|
199,725 |
<p>Can you just trigger <code>wp-cron.php</code> using for example <code>$ php /path/to/wordpress/wp-cron.php</code> rather than going through the wget method using for example <code>wget -q -O - http://example.com/wp-cron.php>/dev/null 2>&1</code>?</p>
|
[
{
"answer_id": 199728,
"author": "Mat",
"author_id": 10914,
"author_profile": "https://wordpress.stackexchange.com/users/10914",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, it's possible to trigger cron runs with just <code>$ php /path/to/wordpress/wp-cron.php</code>.</p>\n\n<p>Alternatively you can use <code>curl</code>:</p>\n\n<pre><code>*/10 * * * * curl http://example.com/wp-cron.php > /dev/null 2>&1\n</code></pre>\n\n<p>And you can add the following line to your <code>wp-config.php</code> to disable crons being run from HTTP requests:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n"
},
{
"answer_id": 332594,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 3,
"selected": false,
"text": "<p>Looking at the file documentation inside <code>wp-cron.php</code> it seems it's absolutely possible to just call <code>$ php wp-cron.php</code>:</p>\n\n<blockquote>\n<pre><code>/**\n * A pseudo-CRON daemon for scheduling WordPress tasks\n *\n * WP Cron is triggered when the site receives a visit. In the scenario\n * where a site may not receive enough visits to execute scheduled tasks\n * in a timely manner, this file can be called directly or via a server\n * CRON daemon for X number of times.\n *\n * Defining DISABLE_WP_CRON as true and calling this file directly are\n * mutually exclusive and the latter does not rely on the former to work.\n *\n * The HTTP request to this file will not slow down the visitor who happens to\n * visit when the cron job is needed to run.\n *\n * @package WordPress\n */\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>What else you can do on the command line, is to use <a href=\"https://wp-cli.org\" rel=\"noreferrer\">wp-cli</a> for that.</p>\n\n<pre><code>$ cd /path/to/wordpress\n$ wp cron event run --due-now\n</code></pre>\n\n<p>To force-trigger one single cron independent from its set schedule run:</p>\n\n<pre><code>$ wp cron event run my_custom_cron_event\n</code></pre>\n\n<p>Or as a one-liner to be used in a crontab to run every full hour + 15 minutes (2:15 pm, 3:15pm, 4:15pm etc.):</p>\n\n<pre><code>15 * * * * cd /path/to/wordpress && wp cron event run --due-now > /dev/null 2>&1\n</code></pre>\n"
}
] |
2015/08/26
|
[
"https://wordpress.stackexchange.com/questions/199725",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78360/"
] |
Can you just trigger `wp-cron.php` using for example `$ php /path/to/wordpress/wp-cron.php` rather than going through the wget method using for example `wget -q -O - http://example.com/wp-cron.php>/dev/null 2>&1`?
|
Yes, it's possible to trigger cron runs with just `$ php /path/to/wordpress/wp-cron.php`.
Alternatively you can use `curl`:
```
*/10 * * * * curl http://example.com/wp-cron.php > /dev/null 2>&1
```
And you can add the following line to your `wp-config.php` to disable crons being run from HTTP requests:
```
define('DISABLE_WP_CRON', true);
```
|
199,767 |
<p>I've got a function that pulls the latest post from each category and arrange categories by latests posts. What I get from this is an array with category ids which I want to use to rearrange the get_categories array.</p>
<pre><code>/* Get all categories */
$categories = get_categories();
/* Create empty array */
$categories_order = [];
/* For each category */
foreach($categories as $category) {
/* Modify WP query */
$args = array('posts_per_page' => 1, /* Max 1 post */
'category__in' => array($category->term_id), /* In this specific category */
'ignore_sticky_posts' => true ); /* No sticky posts */
/* Get all posts from categories with modifier */
$posts = get_posts($args);
/* If there are posts */
if ($posts) {
/* For each post */
foreach($posts as $post) {
/* Add to array key => value (category id => time published) */
$categories_order[$category->term_id] = get_post_time('YmdHis');
}
}
}
arsort($categories_order); /* Order new array by value */
$categories_order = array_keys($categories_order); /* Remove array values */
print_r($categories_order);
</code></pre>
<p>My function returns:</p>
<p><code>Array ( [0] => 2 [1] => 5 [2] => 4 )</code></p>
<p>get_categories returns:</p>
<pre><code>Array
(
[1] => stdClass Object
(
[term_id] => 2
[name] => Спорт
[slug] => sport
[term_group] => 0
[term_taxonomy_id] => 2
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 6
[cat_ID] => 2
[category_count] => 6
[category_description] =>
[cat_name] => Спорт
[category_nicename] => sport
[category_parent] => 0
)
[2] => stdClass Object
(
[term_id] => 4
[name] => Дом и градина
[slug] => home-and-garden
[term_group] => 0
[term_taxonomy_id] => 4
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 1
[cat_ID] => 4
[category_count] => 1
[category_description] =>
[cat_name] => Дом и градина
[category_nicename] => home-and-garden
[category_parent] => 0
)
[3] => stdClass Object
(
[term_id] => 5
[name] => Транспорт
[slug] => transport
[term_group] => 0
[term_taxonomy_id] => 5
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 1
[cat_ID] => 5
[category_count] => 1
[category_description] =>
[cat_name] => Транспорт
[category_nicename] => transport
[category_parent] => 0
)
)
</code></pre>
<p>Now somehow get_categories term_id should be compared to my array and the objects rearranged accordingly.</p>
|
[
{
"answer_id": 199728,
"author": "Mat",
"author_id": 10914,
"author_profile": "https://wordpress.stackexchange.com/users/10914",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, it's possible to trigger cron runs with just <code>$ php /path/to/wordpress/wp-cron.php</code>.</p>\n\n<p>Alternatively you can use <code>curl</code>:</p>\n\n<pre><code>*/10 * * * * curl http://example.com/wp-cron.php > /dev/null 2>&1\n</code></pre>\n\n<p>And you can add the following line to your <code>wp-config.php</code> to disable crons being run from HTTP requests:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n"
},
{
"answer_id": 332594,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 3,
"selected": false,
"text": "<p>Looking at the file documentation inside <code>wp-cron.php</code> it seems it's absolutely possible to just call <code>$ php wp-cron.php</code>:</p>\n\n<blockquote>\n<pre><code>/**\n * A pseudo-CRON daemon for scheduling WordPress tasks\n *\n * WP Cron is triggered when the site receives a visit. In the scenario\n * where a site may not receive enough visits to execute scheduled tasks\n * in a timely manner, this file can be called directly or via a server\n * CRON daemon for X number of times.\n *\n * Defining DISABLE_WP_CRON as true and calling this file directly are\n * mutually exclusive and the latter does not rely on the former to work.\n *\n * The HTTP request to this file will not slow down the visitor who happens to\n * visit when the cron job is needed to run.\n *\n * @package WordPress\n */\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>What else you can do on the command line, is to use <a href=\"https://wp-cli.org\" rel=\"noreferrer\">wp-cli</a> for that.</p>\n\n<pre><code>$ cd /path/to/wordpress\n$ wp cron event run --due-now\n</code></pre>\n\n<p>To force-trigger one single cron independent from its set schedule run:</p>\n\n<pre><code>$ wp cron event run my_custom_cron_event\n</code></pre>\n\n<p>Or as a one-liner to be used in a crontab to run every full hour + 15 minutes (2:15 pm, 3:15pm, 4:15pm etc.):</p>\n\n<pre><code>15 * * * * cd /path/to/wordpress && wp cron event run --due-now > /dev/null 2>&1\n</code></pre>\n"
}
] |
2015/08/26
|
[
"https://wordpress.stackexchange.com/questions/199767",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25900/"
] |
I've got a function that pulls the latest post from each category and arrange categories by latests posts. What I get from this is an array with category ids which I want to use to rearrange the get\_categories array.
```
/* Get all categories */
$categories = get_categories();
/* Create empty array */
$categories_order = [];
/* For each category */
foreach($categories as $category) {
/* Modify WP query */
$args = array('posts_per_page' => 1, /* Max 1 post */
'category__in' => array($category->term_id), /* In this specific category */
'ignore_sticky_posts' => true ); /* No sticky posts */
/* Get all posts from categories with modifier */
$posts = get_posts($args);
/* If there are posts */
if ($posts) {
/* For each post */
foreach($posts as $post) {
/* Add to array key => value (category id => time published) */
$categories_order[$category->term_id] = get_post_time('YmdHis');
}
}
}
arsort($categories_order); /* Order new array by value */
$categories_order = array_keys($categories_order); /* Remove array values */
print_r($categories_order);
```
My function returns:
`Array ( [0] => 2 [1] => 5 [2] => 4 )`
get\_categories returns:
```
Array
(
[1] => stdClass Object
(
[term_id] => 2
[name] => Спорт
[slug] => sport
[term_group] => 0
[term_taxonomy_id] => 2
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 6
[cat_ID] => 2
[category_count] => 6
[category_description] =>
[cat_name] => Спорт
[category_nicename] => sport
[category_parent] => 0
)
[2] => stdClass Object
(
[term_id] => 4
[name] => Дом и градина
[slug] => home-and-garden
[term_group] => 0
[term_taxonomy_id] => 4
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 1
[cat_ID] => 4
[category_count] => 1
[category_description] =>
[cat_name] => Дом и градина
[category_nicename] => home-and-garden
[category_parent] => 0
)
[3] => stdClass Object
(
[term_id] => 5
[name] => Транспорт
[slug] => transport
[term_group] => 0
[term_taxonomy_id] => 5
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 1
[cat_ID] => 5
[category_count] => 1
[category_description] =>
[cat_name] => Транспорт
[category_nicename] => transport
[category_parent] => 0
)
)
```
Now somehow get\_categories term\_id should be compared to my array and the objects rearranged accordingly.
|
Yes, it's possible to trigger cron runs with just `$ php /path/to/wordpress/wp-cron.php`.
Alternatively you can use `curl`:
```
*/10 * * * * curl http://example.com/wp-cron.php > /dev/null 2>&1
```
And you can add the following line to your `wp-config.php` to disable crons being run from HTTP requests:
```
define('DISABLE_WP_CRON', true);
```
|
199,795 |
<p>I have created a custom admin page, which has a bunch of option fields available. One of them I use to enter some HTML code, and I was wondering if it was possible to also add php into that field, for it to be executed when that option is called in my template?</p>
<p>Thanks for any pointers.</p>
|
[
{
"answer_id": 199728,
"author": "Mat",
"author_id": 10914,
"author_profile": "https://wordpress.stackexchange.com/users/10914",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, it's possible to trigger cron runs with just <code>$ php /path/to/wordpress/wp-cron.php</code>.</p>\n\n<p>Alternatively you can use <code>curl</code>:</p>\n\n<pre><code>*/10 * * * * curl http://example.com/wp-cron.php > /dev/null 2>&1\n</code></pre>\n\n<p>And you can add the following line to your <code>wp-config.php</code> to disable crons being run from HTTP requests:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n"
},
{
"answer_id": 332594,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 3,
"selected": false,
"text": "<p>Looking at the file documentation inside <code>wp-cron.php</code> it seems it's absolutely possible to just call <code>$ php wp-cron.php</code>:</p>\n\n<blockquote>\n<pre><code>/**\n * A pseudo-CRON daemon for scheduling WordPress tasks\n *\n * WP Cron is triggered when the site receives a visit. In the scenario\n * where a site may not receive enough visits to execute scheduled tasks\n * in a timely manner, this file can be called directly or via a server\n * CRON daemon for X number of times.\n *\n * Defining DISABLE_WP_CRON as true and calling this file directly are\n * mutually exclusive and the latter does not rely on the former to work.\n *\n * The HTTP request to this file will not slow down the visitor who happens to\n * visit when the cron job is needed to run.\n *\n * @package WordPress\n */\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>What else you can do on the command line, is to use <a href=\"https://wp-cli.org\" rel=\"noreferrer\">wp-cli</a> for that.</p>\n\n<pre><code>$ cd /path/to/wordpress\n$ wp cron event run --due-now\n</code></pre>\n\n<p>To force-trigger one single cron independent from its set schedule run:</p>\n\n<pre><code>$ wp cron event run my_custom_cron_event\n</code></pre>\n\n<p>Or as a one-liner to be used in a crontab to run every full hour + 15 minutes (2:15 pm, 3:15pm, 4:15pm etc.):</p>\n\n<pre><code>15 * * * * cd /path/to/wordpress && wp cron event run --due-now > /dev/null 2>&1\n</code></pre>\n"
}
] |
2015/08/26
|
[
"https://wordpress.stackexchange.com/questions/199795",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47334/"
] |
I have created a custom admin page, which has a bunch of option fields available. One of them I use to enter some HTML code, and I was wondering if it was possible to also add php into that field, for it to be executed when that option is called in my template?
Thanks for any pointers.
|
Yes, it's possible to trigger cron runs with just `$ php /path/to/wordpress/wp-cron.php`.
Alternatively you can use `curl`:
```
*/10 * * * * curl http://example.com/wp-cron.php > /dev/null 2>&1
```
And you can add the following line to your `wp-config.php` to disable crons being run from HTTP requests:
```
define('DISABLE_WP_CRON', true);
```
|
199,798 |
<p>I've just disabled a plugin on my site and it's now giving me the dreaded white screen of death. I know the site will be fine if I reactivate the plugin.</p>
<p>Is there a way to manually activate a plugin through PHPMyAdmin or over FTP?</p>
|
[
{
"answer_id": 199801,
"author": "Karolína Vyskočilová",
"author_id": 64771,
"author_profile": "https://wordpress.stackexchange.com/users/64771",
"pm_score": 2,
"selected": false,
"text": "<p>You can simply rename the plugin folder, for example:</p>\n\n<p><code>\"_aksimet\"</code> to deactive it\nand than back to\n<code>\"aksimet\"</code> to activate it again (if was active)</p>\n\n<p>you can do that with all \"plugins\" folder together.</p>\n\n<p>Otherwise, go to MySQL and have a look at this <a href=\"https://wordpresscheat.com/disable-wordpress-plugin-phpmyadmin-mysql-database/\" rel=\"nofollow\">step by step manual</a>, in short:</p>\n\n<ol>\n<li>MYSQL > <code>wp_options</code></li>\n<li>search for <code>active_plugins</code> entry \n(both steps can be done by <code>SELECT * FROM wp_options WHERE option_name = 'active_plugins';</code>)</li>\n<li>and than write your plugin there as the other plugins are written (<code>i</code> is index, <code>s</code> is for the length of string).</li>\n</ol>\n\n<p>Hope it helps</p>\n"
},
{
"answer_id": 199810,
"author": "Django Reinhardt",
"author_id": 4109,
"author_profile": "https://wordpress.stackexchange.com/users/4109",
"pm_score": 6,
"selected": true,
"text": "<p>I fixed this by going through PHPMyAdmin to the table \"Options\" and then the row <code>active_plugins</code>.</p>\n\n<p>I had the following stored there (formatted for readability):</p>\n\n<pre><code>a:10:{\n i:0;s:49:\"1and1-wordpress-wizard/1and1-wordpress-wizard.php\";\n i:1;s:29:\"acf-repeater/acf-repeater.php\";\n i:2;s:30:\"advanced-custom-fields/acf.php\";\n i:3;s:45:\"limit-login-attempts/limit-login-attempts.php\";\n i:4;s:27:\"redirection/redirection.php\";\n i:6;s:33:\"w3-total-cache/w3-total-cache.php\";\n i:7;s:41:\"wordpress-importer/wordpress-importer.php\";\n i:8;s:24:\"wordpress-seo/wp-seo.php\";\n i:9;s:34:\"wpml-string-translation/plugin.php\";\n i:10;s:38:\"wpml-translation-management/plugin.php\";\n}\n</code></pre>\n\n<p>I added a new line (for the missing plugin) and incremented the <code>a:10</code> to <code>a:11</code> to indicate that there are now 11 items in the array:</p>\n\n<pre><code>a:11:{\n i:0;s:49:\"1and1-wordpress-wizard/1and1-wordpress-wizard.php\";\n i:1;s:29:\"acf-repeater/acf-repeater.php\";\n i:2;s:30:\"advanced-custom-fields/acf.php\";\n i:3;s:45:\"limit-login-attempts/limit-login-attempts.php\";\n i:4;s:27:\"redirection/redirection.php\";\n i:5;s:40:\"sitepress-multilingual-cms/sitepress.php\";\n i:6;s:33:\"w3-total-cache/w3-total-cache.php\";\n i:7;s:41:\"wordpress-importer/wordpress-importer.php\";\n i:8;s:24:\"wordpress-seo/wp-seo.php\";\n i:9;s:34:\"wpml-string-translation/plugin.php\";\n i:10;s:38:\"wpml-translation-management/plugin.php\";\n}\n</code></pre>\n\n<p><code>i:</code> appears to be item number, and thanks to JHoffmann's comment, it appears <code>s:</code> is the length of the string that follows.</p>\n\n<p>The site now works as before!</p>\n"
},
{
"answer_id": 228423,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 3,
"selected": false,
"text": "<p>Just another answer for a different approach that could benefit someone else in the future.\nYou could also move the plugin folder to the Must Use folder (which you will probably need to create if not used before. This path is usually: </p>\n\n<pre><code>wp-content/mu-plugins\n</code></pre>\n\n<p>Plugins in this folder will always run. Refer to the following for more info:</p>\n\n<p><a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"noreferrer\">https://codex.wordpress.org/Must_Use_Plugins</a></p>\n\n<p>Note: The only thing to consider is that these plugins are loaded before others in the plugins folder.\nAlso refer to the caveats in the above link as there may be other issues that could prevent your plugin working correctly.</p>\n"
},
{
"answer_id": 232415,
"author": "Anil Jadhav",
"author_id": 98432,
"author_profile": "https://wordpress.stackexchange.com/users/98432",
"pm_score": 4,
"selected": false,
"text": "<pre><code>//Using this code you can activate your plugin from the functions.php\n function activate_plugin_via_php() {\n $active_plugins = get_option( 'active_plugins' );\n array_push($active_plugins, 'unyson/unyson.php'); /* Here just replace unyson plugin directory and plugin file*/\n update_option( 'active_plugins', $active_plugins ); \n }\n add_action( 'init', 'activate_plugin_via_php' );\n</code></pre>\n"
}
] |
2015/08/26
|
[
"https://wordpress.stackexchange.com/questions/199798",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4109/"
] |
I've just disabled a plugin on my site and it's now giving me the dreaded white screen of death. I know the site will be fine if I reactivate the plugin.
Is there a way to manually activate a plugin through PHPMyAdmin or over FTP?
|
I fixed this by going through PHPMyAdmin to the table "Options" and then the row `active_plugins`.
I had the following stored there (formatted for readability):
```
a:10:{
i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php";
i:1;s:29:"acf-repeater/acf-repeater.php";
i:2;s:30:"advanced-custom-fields/acf.php";
i:3;s:45:"limit-login-attempts/limit-login-attempts.php";
i:4;s:27:"redirection/redirection.php";
i:6;s:33:"w3-total-cache/w3-total-cache.php";
i:7;s:41:"wordpress-importer/wordpress-importer.php";
i:8;s:24:"wordpress-seo/wp-seo.php";
i:9;s:34:"wpml-string-translation/plugin.php";
i:10;s:38:"wpml-translation-management/plugin.php";
}
```
I added a new line (for the missing plugin) and incremented the `a:10` to `a:11` to indicate that there are now 11 items in the array:
```
a:11:{
i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php";
i:1;s:29:"acf-repeater/acf-repeater.php";
i:2;s:30:"advanced-custom-fields/acf.php";
i:3;s:45:"limit-login-attempts/limit-login-attempts.php";
i:4;s:27:"redirection/redirection.php";
i:5;s:40:"sitepress-multilingual-cms/sitepress.php";
i:6;s:33:"w3-total-cache/w3-total-cache.php";
i:7;s:41:"wordpress-importer/wordpress-importer.php";
i:8;s:24:"wordpress-seo/wp-seo.php";
i:9;s:34:"wpml-string-translation/plugin.php";
i:10;s:38:"wpml-translation-management/plugin.php";
}
```
`i:` appears to be item number, and thanks to JHoffmann's comment, it appears `s:` is the length of the string that follows.
The site now works as before!
|
199,813 |
<p>Is it possible to change the labels for "Weak, Medium, Strong" etc... in the Password Indicator that's used in the user profile? I've been asked to change the word "Weak" to "OK" since this level of passwords is acceptable for our subscribers. Is there a filter I can hook into?</p>
|
[
{
"answer_id": 199815,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it right in your theme localization file. </p>\n\n<p>Open <code>*.pot</code> file and create the translations for labels you need, e. g. <code>OK</code> for <code>Weak</code>.</p>\n\n<p>See <code>password-strength-meter</code> around line <code>#366</code> in <code>/wp-includes/script-loader.php</code> for the reference (but don't change there anything).</p>\n\n<p><strong>Update</strong>:</p>\n\n<p>I've found the solution using jQuery for the similar problem, but you have to simplify that code to use only one password meter: <a href=\"https://wordpress.stackexchange.com/questions/42596/how-to-use-wordpress-default-password-strength-meter-script\">How to use wordpress default Password Strength Meter script</a>. Also see <code>/wp-admin/js/user-profile.js</code> for reference because that solution is pretty old.</p>\n"
},
{
"answer_id": 199826,
"author": "feelinferrety",
"author_id": 48824,
"author_profile": "https://wordpress.stackexchange.com/users/48824",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.webtipblog.com/force-password-complexity-requirements-wordpress/\" rel=\"nofollow\">This post on Web Tips</a> hooks into a few choice actions and filters to modify password strength allowances, but commenters seemed to have some trouble with it, so take this bit with a grain of salt.</p>\n\n<pre><code>// functions.php\n\nadd_action( 'user_profile_update_errors', 'validateProfileUpdate', 10, 3 );\nadd_filter( 'registration_errors', 'validateRegistration', 10, 3 );\nadd_action( 'validate_password_reset', 'validatePasswordReset', 10, 2 );\n\n/**\n * validate profile update\n *\n * @author Joe Sexton <[email protected]>\n * @param WP_Error $errors\n * @param boolean $update\n * @param object $user raw user object not a WP_User\n */\npublic function validateProfileUpdate( WP_Error &$errors, $update, &$user ) {\n return validateComplexPassword( $errors );\n}\n\n/**\n * validate registration\n *\n * @author Joe Sexton <[email protected]>\n * @param WP_Error $errors\n * @param string $sanitized_user_login\n * @param string $user_email\n * @return WP_Error\n */\nfunction validateRegistration( WP_Error &$errors, $sanitized_user_login, $user_email ) {\n return validateComplexPassword( $errors );\n}\n\n/**\n * validate password reset\n *\n * @author Joe Sexton <[email protected]>\n * @param WP_Error $errors\n * @param stdClass $userData\n * @return WP_Error\n */\nfunction validatePasswordReset( WP_Error &$errors, $userData ) {\n return validateComplexPassword( $errors );\n}\n\n/**\n * validate complex password\n *\n * @author Joe Sexton <[email protected]>\n * @param WP_Error $errors\n * @param stdClass $userData\n * @return WP_Error\n */\nfunction validateComplexPassword( $errors ) {\n $password = ( isset( $_POST[ 'pass1' ] ) && trim( $_POST[ 'pass1' ] ) ) ? $_POST[ 'pass1' ] : null;\n\n // no password or already has password error\n if ( empty( $password ) || ( $errors->get_error_data( 'pass' ) ) )\n return $errors;\n\n // validate\n if ( ! isStrongPassword( $password ) )\n $errors->add( 'pass', '<strong>ERROR</strong>: Your password must contain at least 8 characters.' ); // your complex password error message\n\n return $errors;\n}\n\n/**\n * isStrongPassword\n *\n * @author Joe Sexton <[email protected]>\n * @param string $password\n * @return boolean\n */\nfunction isStrongPassword( $password ) {\n return strlen( $password ) >= 8; // your complex password algorithm\n}\n</code></pre>\n\n<p>If you can't get the hooking route to work or if you have a custom login page, <a href=\"http://code.tutsplus.com/articles/using-the-included-password-strength-meter-script-in-wordpress--wp-34736\" rel=\"nofollow\">this post on Tuts Plus</a> has a handy tutorial for utilizing the existing script on your own forms.</p>\n\n<p>Add to <code>functions.php</code>:</p>\n\n<pre><code>wp_enqueue_script( 'password-strength-meter' );\n</code></pre>\n\n<p>In your HTML:</p>\n\n<pre><code><form>\n <input type=\"password\" name=\"password\" />\n <input type=\"password\" name=\"password_retyped\" />\n <span id=\"password-strength\"></span>\n <input type=\"submit\" disabled=\"disabled\" value=\"Submit\" />\n</form>\n</code></pre>\n\n<p>The script:</p>\n\n<pre><code>function checkPasswordStrength( $pass1,\n $pass2,\n $strengthResult,\n $submitButton,\n blacklistArray ) {\n var pass1 = $pass1.val();\n var pass2 = $pass2.val();\n\n // Reset the form & meter\n $submitButton.attr( 'disabled', 'disabled' );\n $strengthResult.removeClass( 'short bad good strong' );\n\n // Extend our blacklist array with those from the inputs & site data\n blacklistArray = blacklistArray.concat( wp.passwordStrength.userInputBlacklist() )\n\n // Get the password strength\n var strength = wp.passwordStrength.meter( pass1, blacklistArray, pass2 );\n\n // Add the strength meter results\n switch ( strength ) {\n\n case 2:\n $strengthResult.addClass( 'bad' ).html( pwsL10n.bad );\n break;\n\n case 3:\n $strengthResult.addClass( 'good' ).html( pwsL10n.good );\n break;\n\n case 4:\n $strengthResult.addClass( 'strong' ).html( pwsL10n.strong );\n break;\n\n case 5:\n $strengthResult.addClass( 'short' ).html( pwsL10n.mismatch );\n break;\n\n default:\n $strengthResult.addClass( 'short' ).html( pwsL10n.short );\n\n }\n\n // The meter function returns a result even if pass2 is empty,\n // enable only the submit button if the password is strong and\n // both passwords are filled up\n if ( 4 === strength && '' !== pass2.trim() ) {\n $submitButton.removeAttr( 'disabled' );\n }\n\n return strength;\n}\n\njQuery( document ).ready( function( $ ) {\n // Binding to trigger checkPasswordStrength\n $( 'body' ).on( 'keyup', 'input[name=password1], input[name=password2]',\n function( event ) {\n checkPasswordStrength(\n $('input[name=password]'), // First password field\n $('input[name=password_retyped]'), // Second password field\n $('#password-strength'), // Strength meter\n $('input[type=submit]'), // Submit button\n ['black', 'listed', 'word'] // Blacklisted words\n );\n }\n );\n});\n</code></pre>\n"
},
{
"answer_id": 199834,
"author": "czerspalace",
"author_id": 47406,
"author_profile": "https://wordpress.stackexchange.com/users/47406",
"pm_score": 1,
"selected": false,
"text": "<p>The \"Weak\" text is passed through <code>_x</code> function, which calls <code>translate_with_gettext_context</code>, so I would try the following:</p>\n\n<pre><code>add_filter( 'gettext_with_context', 'wpse199813_change_password_indicatior', 10, 4 );\n\nfunction wpse199813_change_password_indicatior($translations, $text, $context, $domain){\n\n if( $text == \"Weak\" && $context == \"password strength\")\n return \"OK\";\n\n return $translations;\n}\n</code></pre>\n"
},
{
"answer_id": 199938,
"author": "LBF",
"author_id": 31345,
"author_profile": "https://wordpress.stackexchange.com/users/31345",
"pm_score": 1,
"selected": true,
"text": "<p>I was able to fix it with this method. Is this good/bad? It's working, but I'd be interested in feedback in case this could have unexpected consequences.</p>\n\n<pre><code>add_filter('gettext', 'translate_text'); \nadd_filter('ngettext', 'translate_text');\n\nfunction translate_text($translated) { \n$translated = str_ireplace('Very Weak', 'Bad', $translated); \n$translated = str_ireplace('Weak', 'OK', $translated); \n\nreturn $translated; \n}\n</code></pre>\n"
},
{
"answer_id": 294762,
"author": "dragoweb",
"author_id": 99073,
"author_profile": "https://wordpress.stackexchange.com/users/99073",
"pm_score": 2,
"selected": false,
"text": "<p>Adding this to my function.php file in the child theme folder did it for me:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_strength_meter_localize_script' );\nfunction my_strength_meter_localize_script() {\n wp_localize_script( 'password-strength-meter', 'pwsL10n', array(\n 'empty' => __( 'But... it\\'s empty!', 'theme-domain' ),\n 'short' => __( 'Too short!', 'theme-domain' ),\n 'bad' => __( 'Not even close!', 'theme-domain' ),\n 'good' => __( 'You are getting closer...', 'theme-domain' ),\n 'strong' => __( 'Now, that\\'s a password!', 'theme-domain' ),\n 'mismatch' => __( 'They are completely different, come on!', 'theme-domain' )\n ) );\n}\n</code></pre>\n\n<p><a href=\"https://nicola.blog/2016/02/16/change-the-password-strength-meter-labels/\" rel=\"nofollow noreferrer\"><strong>Source</strong></a></p>\n"
}
] |
2015/08/26
|
[
"https://wordpress.stackexchange.com/questions/199813",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31345/"
] |
Is it possible to change the labels for "Weak, Medium, Strong" etc... in the Password Indicator that's used in the user profile? I've been asked to change the word "Weak" to "OK" since this level of passwords is acceptable for our subscribers. Is there a filter I can hook into?
|
I was able to fix it with this method. Is this good/bad? It's working, but I'd be interested in feedback in case this could have unexpected consequences.
```
add_filter('gettext', 'translate_text');
add_filter('ngettext', 'translate_text');
function translate_text($translated) {
$translated = str_ireplace('Very Weak', 'Bad', $translated);
$translated = str_ireplace('Weak', 'OK', $translated);
return $translated;
}
```
|
199,840 |
<p>I want to display the url's like this:</p>
<p>for Category:
/webshop/categories/hoodies/</p>
<p>for products:</p>
<p>/webshop/categories/hoodies/test-product</p>
<p>how is this possible without giving me 404 not found</p>
<p>thanks</p>
|
[
{
"answer_id": 199815,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it right in your theme localization file. </p>\n\n<p>Open <code>*.pot</code> file and create the translations for labels you need, e. g. <code>OK</code> for <code>Weak</code>.</p>\n\n<p>See <code>password-strength-meter</code> around line <code>#366</code> in <code>/wp-includes/script-loader.php</code> for the reference (but don't change there anything).</p>\n\n<p><strong>Update</strong>:</p>\n\n<p>I've found the solution using jQuery for the similar problem, but you have to simplify that code to use only one password meter: <a href=\"https://wordpress.stackexchange.com/questions/42596/how-to-use-wordpress-default-password-strength-meter-script\">How to use wordpress default Password Strength Meter script</a>. Also see <code>/wp-admin/js/user-profile.js</code> for reference because that solution is pretty old.</p>\n"
},
{
"answer_id": 199826,
"author": "feelinferrety",
"author_id": 48824,
"author_profile": "https://wordpress.stackexchange.com/users/48824",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.webtipblog.com/force-password-complexity-requirements-wordpress/\" rel=\"nofollow\">This post on Web Tips</a> hooks into a few choice actions and filters to modify password strength allowances, but commenters seemed to have some trouble with it, so take this bit with a grain of salt.</p>\n\n<pre><code>// functions.php\n\nadd_action( 'user_profile_update_errors', 'validateProfileUpdate', 10, 3 );\nadd_filter( 'registration_errors', 'validateRegistration', 10, 3 );\nadd_action( 'validate_password_reset', 'validatePasswordReset', 10, 2 );\n\n/**\n * validate profile update\n *\n * @author Joe Sexton <[email protected]>\n * @param WP_Error $errors\n * @param boolean $update\n * @param object $user raw user object not a WP_User\n */\npublic function validateProfileUpdate( WP_Error &$errors, $update, &$user ) {\n return validateComplexPassword( $errors );\n}\n\n/**\n * validate registration\n *\n * @author Joe Sexton <[email protected]>\n * @param WP_Error $errors\n * @param string $sanitized_user_login\n * @param string $user_email\n * @return WP_Error\n */\nfunction validateRegistration( WP_Error &$errors, $sanitized_user_login, $user_email ) {\n return validateComplexPassword( $errors );\n}\n\n/**\n * validate password reset\n *\n * @author Joe Sexton <[email protected]>\n * @param WP_Error $errors\n * @param stdClass $userData\n * @return WP_Error\n */\nfunction validatePasswordReset( WP_Error &$errors, $userData ) {\n return validateComplexPassword( $errors );\n}\n\n/**\n * validate complex password\n *\n * @author Joe Sexton <[email protected]>\n * @param WP_Error $errors\n * @param stdClass $userData\n * @return WP_Error\n */\nfunction validateComplexPassword( $errors ) {\n $password = ( isset( $_POST[ 'pass1' ] ) && trim( $_POST[ 'pass1' ] ) ) ? $_POST[ 'pass1' ] : null;\n\n // no password or already has password error\n if ( empty( $password ) || ( $errors->get_error_data( 'pass' ) ) )\n return $errors;\n\n // validate\n if ( ! isStrongPassword( $password ) )\n $errors->add( 'pass', '<strong>ERROR</strong>: Your password must contain at least 8 characters.' ); // your complex password error message\n\n return $errors;\n}\n\n/**\n * isStrongPassword\n *\n * @author Joe Sexton <[email protected]>\n * @param string $password\n * @return boolean\n */\nfunction isStrongPassword( $password ) {\n return strlen( $password ) >= 8; // your complex password algorithm\n}\n</code></pre>\n\n<p>If you can't get the hooking route to work or if you have a custom login page, <a href=\"http://code.tutsplus.com/articles/using-the-included-password-strength-meter-script-in-wordpress--wp-34736\" rel=\"nofollow\">this post on Tuts Plus</a> has a handy tutorial for utilizing the existing script on your own forms.</p>\n\n<p>Add to <code>functions.php</code>:</p>\n\n<pre><code>wp_enqueue_script( 'password-strength-meter' );\n</code></pre>\n\n<p>In your HTML:</p>\n\n<pre><code><form>\n <input type=\"password\" name=\"password\" />\n <input type=\"password\" name=\"password_retyped\" />\n <span id=\"password-strength\"></span>\n <input type=\"submit\" disabled=\"disabled\" value=\"Submit\" />\n</form>\n</code></pre>\n\n<p>The script:</p>\n\n<pre><code>function checkPasswordStrength( $pass1,\n $pass2,\n $strengthResult,\n $submitButton,\n blacklistArray ) {\n var pass1 = $pass1.val();\n var pass2 = $pass2.val();\n\n // Reset the form & meter\n $submitButton.attr( 'disabled', 'disabled' );\n $strengthResult.removeClass( 'short bad good strong' );\n\n // Extend our blacklist array with those from the inputs & site data\n blacklistArray = blacklistArray.concat( wp.passwordStrength.userInputBlacklist() )\n\n // Get the password strength\n var strength = wp.passwordStrength.meter( pass1, blacklistArray, pass2 );\n\n // Add the strength meter results\n switch ( strength ) {\n\n case 2:\n $strengthResult.addClass( 'bad' ).html( pwsL10n.bad );\n break;\n\n case 3:\n $strengthResult.addClass( 'good' ).html( pwsL10n.good );\n break;\n\n case 4:\n $strengthResult.addClass( 'strong' ).html( pwsL10n.strong );\n break;\n\n case 5:\n $strengthResult.addClass( 'short' ).html( pwsL10n.mismatch );\n break;\n\n default:\n $strengthResult.addClass( 'short' ).html( pwsL10n.short );\n\n }\n\n // The meter function returns a result even if pass2 is empty,\n // enable only the submit button if the password is strong and\n // both passwords are filled up\n if ( 4 === strength && '' !== pass2.trim() ) {\n $submitButton.removeAttr( 'disabled' );\n }\n\n return strength;\n}\n\njQuery( document ).ready( function( $ ) {\n // Binding to trigger checkPasswordStrength\n $( 'body' ).on( 'keyup', 'input[name=password1], input[name=password2]',\n function( event ) {\n checkPasswordStrength(\n $('input[name=password]'), // First password field\n $('input[name=password_retyped]'), // Second password field\n $('#password-strength'), // Strength meter\n $('input[type=submit]'), // Submit button\n ['black', 'listed', 'word'] // Blacklisted words\n );\n }\n );\n});\n</code></pre>\n"
},
{
"answer_id": 199834,
"author": "czerspalace",
"author_id": 47406,
"author_profile": "https://wordpress.stackexchange.com/users/47406",
"pm_score": 1,
"selected": false,
"text": "<p>The \"Weak\" text is passed through <code>_x</code> function, which calls <code>translate_with_gettext_context</code>, so I would try the following:</p>\n\n<pre><code>add_filter( 'gettext_with_context', 'wpse199813_change_password_indicatior', 10, 4 );\n\nfunction wpse199813_change_password_indicatior($translations, $text, $context, $domain){\n\n if( $text == \"Weak\" && $context == \"password strength\")\n return \"OK\";\n\n return $translations;\n}\n</code></pre>\n"
},
{
"answer_id": 199938,
"author": "LBF",
"author_id": 31345,
"author_profile": "https://wordpress.stackexchange.com/users/31345",
"pm_score": 1,
"selected": true,
"text": "<p>I was able to fix it with this method. Is this good/bad? It's working, but I'd be interested in feedback in case this could have unexpected consequences.</p>\n\n<pre><code>add_filter('gettext', 'translate_text'); \nadd_filter('ngettext', 'translate_text');\n\nfunction translate_text($translated) { \n$translated = str_ireplace('Very Weak', 'Bad', $translated); \n$translated = str_ireplace('Weak', 'OK', $translated); \n\nreturn $translated; \n}\n</code></pre>\n"
},
{
"answer_id": 294762,
"author": "dragoweb",
"author_id": 99073,
"author_profile": "https://wordpress.stackexchange.com/users/99073",
"pm_score": 2,
"selected": false,
"text": "<p>Adding this to my function.php file in the child theme folder did it for me:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_strength_meter_localize_script' );\nfunction my_strength_meter_localize_script() {\n wp_localize_script( 'password-strength-meter', 'pwsL10n', array(\n 'empty' => __( 'But... it\\'s empty!', 'theme-domain' ),\n 'short' => __( 'Too short!', 'theme-domain' ),\n 'bad' => __( 'Not even close!', 'theme-domain' ),\n 'good' => __( 'You are getting closer...', 'theme-domain' ),\n 'strong' => __( 'Now, that\\'s a password!', 'theme-domain' ),\n 'mismatch' => __( 'They are completely different, come on!', 'theme-domain' )\n ) );\n}\n</code></pre>\n\n<p><a href=\"https://nicola.blog/2016/02/16/change-the-password-strength-meter-labels/\" rel=\"nofollow noreferrer\"><strong>Source</strong></a></p>\n"
}
] |
2015/08/26
|
[
"https://wordpress.stackexchange.com/questions/199840",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52269/"
] |
I want to display the url's like this:
for Category:
/webshop/categories/hoodies/
for products:
/webshop/categories/hoodies/test-product
how is this possible without giving me 404 not found
thanks
|
I was able to fix it with this method. Is this good/bad? It's working, but I'd be interested in feedback in case this could have unexpected consequences.
```
add_filter('gettext', 'translate_text');
add_filter('ngettext', 'translate_text');
function translate_text($translated) {
$translated = str_ireplace('Very Weak', 'Bad', $translated);
$translated = str_ireplace('Weak', 'OK', $translated);
return $translated;
}
```
|
199,844 |
<p>Are there any example projects that do the same? </p>
<p>I want to be able to login and register for accounts on my site via the API.</p>
|
[
{
"answer_id": 219446,
"author": "Joe Dooley",
"author_id": 81789,
"author_profile": "https://wordpress.stackexchange.com/users/81789",
"pm_score": 1,
"selected": false,
"text": "<p>There are a lot of examples of user registration using the WP REST API and the OAuth server implementation for WP API <a href=\"http://oauth1.wp-api.org/\" rel=\"nofollow\">http://oauth1.wp-api.org/</a>.</p>\n\n<p>I'm sure there were less 6 months ago when you originally posted but here are a couple of great examples that will get you going.</p>\n\n<ul>\n<li><a href=\"https://github.com/WP-API/example-client\" rel=\"nofollow\">Example OAuth Client</a></li>\n<li><a href=\"http://code.tutsplus.com/tutorials/wp-rest-api-setting-up-and-using-oauth-10a-authentication--cms-24797\" rel=\"nofollow\">WP REST API: Setting Up and Using OAuth 1.0a Authentication</a></li>\n<li><a href=\"https://github.com/WP-API/OAuth1/tree/master/docs\" rel=\"nofollow\">OAuth Docs</a></li>\n</ul>\n\n<p>There are also a few plugins starting to surface.</p>\n"
},
{
"answer_id": 302331,
"author": "Jack Song",
"author_id": 134082,
"author_profile": "https://wordpress.stackexchange.com/users/134082",
"pm_score": 2,
"selected": false,
"text": "<p>I know it's a bit far fetched, but might help. For anyone looking for WP REST API implementation with JWT, here's our solution. </p>\n\n<p>Add it to your function.php</p>\n\n<pre><code>add_action('rest_api_init', 'wp_rest_user_endpoints');\n/**\n * Register a new user\n *\n * @param WP_REST_Request $request Full details about the request.\n * @return array $args.\n **/\nfunction wp_rest_user_endpoints($request) {\n /**\n * Handle Register User request.\n */\n register_rest_route('wp/v2', 'users/register', array(\n 'methods' => 'POST',\n 'callback' => 'wc_rest_user_endpoint_handler',\n ));\n}\nfunction wc_rest_user_endpoint_handler($request = null) {\n $response = array();\n $parameters = $request->get_json_params();\n $username = sanitize_text_field($parameters['username']);\n $email = sanitize_text_field($parameters['email']);\n $password = sanitize_text_field($parameters['password']);\n // $role = sanitize_text_field($parameters['role']);\n $error = new WP_Error();\n if (empty($username)) {\n $error->add(400, __(\"Username field 'username' is required.\", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n if (empty($email)) {\n $error->add(401, __(\"Email field 'email' is required.\", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n if (empty($password)) {\n $error->add(404, __(\"Password field 'password' is required.\", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n // if (empty($role)) {\n // $role = 'subscriber';\n // } else {\n // if ($GLOBALS['wp_roles']->is_role($role)) {\n // // Silence is gold\n // } else {\n // $error->add(405, __(\"Role field 'role' is not a valid. Check your User Roles from Dashboard.\", 'wp_rest_user'), array('status' => 400));\n // return $error;\n // }\n // }\n $user_id = username_exists($username);\n if (!$user_id && email_exists($email) == false) {\n $user_id = wp_create_user($username, $password, $email);\n if (!is_wp_error($user_id)) {\n // Ger User Meta Data (Sensitive, Password included. DO NOT pass to front end.)\n $user = get_user_by('id', $user_id);\n // $user->set_role($role);\n $user->set_role('subscriber');\n // WooCommerce specific code\n if (class_exists('WooCommerce')) {\n $user->set_role('customer');\n }\n // Ger User Data (Non-Sensitive, Pass to front end.)\n $response['code'] = 200;\n $response['message'] = __(\"User '\" . $username . \"' Registration was Successful\", \"wp-rest-user\");\n } else {\n return $user_id;\n }\n } else {\n $error->add(406, __(\"Email already exists, please try 'Reset Password'\", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n return new WP_REST_Response($response, 123);\n}\n</code></pre>\n\n<p>IMHO, a more better way would to include the additional function as a seperate plugin. So even when your user changed theme, your api calls won't be affected.</p>\n\n<p>Therefore I've developed a <strong>plugin</strong> for User Registration via REST API in WordPress. Better yet, it supports creating 'customer' for WooCommerce too!</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-rest-user/\" rel=\"nofollow noreferrer\">WP REST User</a>, check it out if you want. </p>\n"
}
] |
2015/08/26
|
[
"https://wordpress.stackexchange.com/questions/199844",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78405/"
] |
Are there any example projects that do the same?
I want to be able to login and register for accounts on my site via the API.
|
I know it's a bit far fetched, but might help. For anyone looking for WP REST API implementation with JWT, here's our solution.
Add it to your function.php
```
add_action('rest_api_init', 'wp_rest_user_endpoints');
/**
* Register a new user
*
* @param WP_REST_Request $request Full details about the request.
* @return array $args.
**/
function wp_rest_user_endpoints($request) {
/**
* Handle Register User request.
*/
register_rest_route('wp/v2', 'users/register', array(
'methods' => 'POST',
'callback' => 'wc_rest_user_endpoint_handler',
));
}
function wc_rest_user_endpoint_handler($request = null) {
$response = array();
$parameters = $request->get_json_params();
$username = sanitize_text_field($parameters['username']);
$email = sanitize_text_field($parameters['email']);
$password = sanitize_text_field($parameters['password']);
// $role = sanitize_text_field($parameters['role']);
$error = new WP_Error();
if (empty($username)) {
$error->add(400, __("Username field 'username' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
if (empty($email)) {
$error->add(401, __("Email field 'email' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
if (empty($password)) {
$error->add(404, __("Password field 'password' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
// if (empty($role)) {
// $role = 'subscriber';
// } else {
// if ($GLOBALS['wp_roles']->is_role($role)) {
// // Silence is gold
// } else {
// $error->add(405, __("Role field 'role' is not a valid. Check your User Roles from Dashboard.", 'wp_rest_user'), array('status' => 400));
// return $error;
// }
// }
$user_id = username_exists($username);
if (!$user_id && email_exists($email) == false) {
$user_id = wp_create_user($username, $password, $email);
if (!is_wp_error($user_id)) {
// Ger User Meta Data (Sensitive, Password included. DO NOT pass to front end.)
$user = get_user_by('id', $user_id);
// $user->set_role($role);
$user->set_role('subscriber');
// WooCommerce specific code
if (class_exists('WooCommerce')) {
$user->set_role('customer');
}
// Ger User Data (Non-Sensitive, Pass to front end.)
$response['code'] = 200;
$response['message'] = __("User '" . $username . "' Registration was Successful", "wp-rest-user");
} else {
return $user_id;
}
} else {
$error->add(406, __("Email already exists, please try 'Reset Password'", 'wp-rest-user'), array('status' => 400));
return $error;
}
return new WP_REST_Response($response, 123);
}
```
IMHO, a more better way would to include the additional function as a seperate plugin. So even when your user changed theme, your api calls won't be affected.
Therefore I've developed a **plugin** for User Registration via REST API in WordPress. Better yet, it supports creating 'customer' for WooCommerce too!
[WP REST User](https://wordpress.org/plugins/wp-rest-user/), check it out if you want.
|
199,849 |
<p>Im starting the biggest project I ever made, a online business directory in a certain niche.</p>
<p>Firstly, I thought to make two wordpress installs sharing the same database and specially the users table. Like website/blog.</p>
<p>I.e. niche-directory in the main domain and in a subdirectory a blog.</p>
<p>I want to blog about that niche while Im developing the main website.</p>
<p>Besides that, I plan for the future add others small websites in specific topics related to this same niche. And these websites has to share the same users table.</p>
<p>What is important to me is sharing of the users table, so if a user subscribe in one site he/she has automatic login on the others.</p>
<p>But these different websites, even been from the same niche, doesnt share content between each other.</p>
<p>Is Multisite for this case?
I want hear suggestions.</p>
<p>Thanks!!!</p>
|
[
{
"answer_id": 219446,
"author": "Joe Dooley",
"author_id": 81789,
"author_profile": "https://wordpress.stackexchange.com/users/81789",
"pm_score": 1,
"selected": false,
"text": "<p>There are a lot of examples of user registration using the WP REST API and the OAuth server implementation for WP API <a href=\"http://oauth1.wp-api.org/\" rel=\"nofollow\">http://oauth1.wp-api.org/</a>.</p>\n\n<p>I'm sure there were less 6 months ago when you originally posted but here are a couple of great examples that will get you going.</p>\n\n<ul>\n<li><a href=\"https://github.com/WP-API/example-client\" rel=\"nofollow\">Example OAuth Client</a></li>\n<li><a href=\"http://code.tutsplus.com/tutorials/wp-rest-api-setting-up-and-using-oauth-10a-authentication--cms-24797\" rel=\"nofollow\">WP REST API: Setting Up and Using OAuth 1.0a Authentication</a></li>\n<li><a href=\"https://github.com/WP-API/OAuth1/tree/master/docs\" rel=\"nofollow\">OAuth Docs</a></li>\n</ul>\n\n<p>There are also a few plugins starting to surface.</p>\n"
},
{
"answer_id": 302331,
"author": "Jack Song",
"author_id": 134082,
"author_profile": "https://wordpress.stackexchange.com/users/134082",
"pm_score": 2,
"selected": false,
"text": "<p>I know it's a bit far fetched, but might help. For anyone looking for WP REST API implementation with JWT, here's our solution. </p>\n\n<p>Add it to your function.php</p>\n\n<pre><code>add_action('rest_api_init', 'wp_rest_user_endpoints');\n/**\n * Register a new user\n *\n * @param WP_REST_Request $request Full details about the request.\n * @return array $args.\n **/\nfunction wp_rest_user_endpoints($request) {\n /**\n * Handle Register User request.\n */\n register_rest_route('wp/v2', 'users/register', array(\n 'methods' => 'POST',\n 'callback' => 'wc_rest_user_endpoint_handler',\n ));\n}\nfunction wc_rest_user_endpoint_handler($request = null) {\n $response = array();\n $parameters = $request->get_json_params();\n $username = sanitize_text_field($parameters['username']);\n $email = sanitize_text_field($parameters['email']);\n $password = sanitize_text_field($parameters['password']);\n // $role = sanitize_text_field($parameters['role']);\n $error = new WP_Error();\n if (empty($username)) {\n $error->add(400, __(\"Username field 'username' is required.\", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n if (empty($email)) {\n $error->add(401, __(\"Email field 'email' is required.\", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n if (empty($password)) {\n $error->add(404, __(\"Password field 'password' is required.\", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n // if (empty($role)) {\n // $role = 'subscriber';\n // } else {\n // if ($GLOBALS['wp_roles']->is_role($role)) {\n // // Silence is gold\n // } else {\n // $error->add(405, __(\"Role field 'role' is not a valid. Check your User Roles from Dashboard.\", 'wp_rest_user'), array('status' => 400));\n // return $error;\n // }\n // }\n $user_id = username_exists($username);\n if (!$user_id && email_exists($email) == false) {\n $user_id = wp_create_user($username, $password, $email);\n if (!is_wp_error($user_id)) {\n // Ger User Meta Data (Sensitive, Password included. DO NOT pass to front end.)\n $user = get_user_by('id', $user_id);\n // $user->set_role($role);\n $user->set_role('subscriber');\n // WooCommerce specific code\n if (class_exists('WooCommerce')) {\n $user->set_role('customer');\n }\n // Ger User Data (Non-Sensitive, Pass to front end.)\n $response['code'] = 200;\n $response['message'] = __(\"User '\" . $username . \"' Registration was Successful\", \"wp-rest-user\");\n } else {\n return $user_id;\n }\n } else {\n $error->add(406, __(\"Email already exists, please try 'Reset Password'\", 'wp-rest-user'), array('status' => 400));\n return $error;\n }\n return new WP_REST_Response($response, 123);\n}\n</code></pre>\n\n<p>IMHO, a more better way would to include the additional function as a seperate plugin. So even when your user changed theme, your api calls won't be affected.</p>\n\n<p>Therefore I've developed a <strong>plugin</strong> for User Registration via REST API in WordPress. Better yet, it supports creating 'customer' for WooCommerce too!</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-rest-user/\" rel=\"nofollow noreferrer\">WP REST User</a>, check it out if you want. </p>\n"
}
] |
2015/08/26
|
[
"https://wordpress.stackexchange.com/questions/199849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78409/"
] |
Im starting the biggest project I ever made, a online business directory in a certain niche.
Firstly, I thought to make two wordpress installs sharing the same database and specially the users table. Like website/blog.
I.e. niche-directory in the main domain and in a subdirectory a blog.
I want to blog about that niche while Im developing the main website.
Besides that, I plan for the future add others small websites in specific topics related to this same niche. And these websites has to share the same users table.
What is important to me is sharing of the users table, so if a user subscribe in one site he/she has automatic login on the others.
But these different websites, even been from the same niche, doesnt share content between each other.
Is Multisite for this case?
I want hear suggestions.
Thanks!!!
|
I know it's a bit far fetched, but might help. For anyone looking for WP REST API implementation with JWT, here's our solution.
Add it to your function.php
```
add_action('rest_api_init', 'wp_rest_user_endpoints');
/**
* Register a new user
*
* @param WP_REST_Request $request Full details about the request.
* @return array $args.
**/
function wp_rest_user_endpoints($request) {
/**
* Handle Register User request.
*/
register_rest_route('wp/v2', 'users/register', array(
'methods' => 'POST',
'callback' => 'wc_rest_user_endpoint_handler',
));
}
function wc_rest_user_endpoint_handler($request = null) {
$response = array();
$parameters = $request->get_json_params();
$username = sanitize_text_field($parameters['username']);
$email = sanitize_text_field($parameters['email']);
$password = sanitize_text_field($parameters['password']);
// $role = sanitize_text_field($parameters['role']);
$error = new WP_Error();
if (empty($username)) {
$error->add(400, __("Username field 'username' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
if (empty($email)) {
$error->add(401, __("Email field 'email' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
if (empty($password)) {
$error->add(404, __("Password field 'password' is required.", 'wp-rest-user'), array('status' => 400));
return $error;
}
// if (empty($role)) {
// $role = 'subscriber';
// } else {
// if ($GLOBALS['wp_roles']->is_role($role)) {
// // Silence is gold
// } else {
// $error->add(405, __("Role field 'role' is not a valid. Check your User Roles from Dashboard.", 'wp_rest_user'), array('status' => 400));
// return $error;
// }
// }
$user_id = username_exists($username);
if (!$user_id && email_exists($email) == false) {
$user_id = wp_create_user($username, $password, $email);
if (!is_wp_error($user_id)) {
// Ger User Meta Data (Sensitive, Password included. DO NOT pass to front end.)
$user = get_user_by('id', $user_id);
// $user->set_role($role);
$user->set_role('subscriber');
// WooCommerce specific code
if (class_exists('WooCommerce')) {
$user->set_role('customer');
}
// Ger User Data (Non-Sensitive, Pass to front end.)
$response['code'] = 200;
$response['message'] = __("User '" . $username . "' Registration was Successful", "wp-rest-user");
} else {
return $user_id;
}
} else {
$error->add(406, __("Email already exists, please try 'Reset Password'", 'wp-rest-user'), array('status' => 400));
return $error;
}
return new WP_REST_Response($response, 123);
}
```
IMHO, a more better way would to include the additional function as a seperate plugin. So even when your user changed theme, your api calls won't be affected.
Therefore I've developed a **plugin** for User Registration via REST API in WordPress. Better yet, it supports creating 'customer' for WooCommerce too!
[WP REST User](https://wordpress.org/plugins/wp-rest-user/), check it out if you want.
|
199,860 |
<p>I am trying to display authors comments on their profile page (author.php), however both codes I tried seem to display everyone's comments. Also the second code is suppose to link to the specific comment, but instead it does nothing. Also the comments id is already added to the comments output and it prints fine. Any help is greatly appreciated.</p>
<pre><code>// Method 1
<ul class="authpcom">
<?php
$author_email = get_the_author_meta( 'user_email' );
$args = array(
'author_email' => $author_email
);
$comments = get_comments($args);
foreach($comments as $comment) :
echo('<a href=" ' . get_permalink($comment->post_ID) . ' " rel="external nofollow" title=" ' . $title . ' ">' .$title . '</a><br />' . $comment->comment_date . '<br /><li>' . $comment->comment_content . '</li>');
endforeach;
?>
</ul>
// Method 2
<?php $comments = get_comments(); ?>
<ul id="recent_comments">
<?php foreach ($comments as $comment) { ?>
<li><p><strong><?php
$title = get_the_title($comment->comment_post_ID);
echo get_avatar( $comment, '45' );
echo strip_tags($comment->comment_author); ?></strong>&nbsp;commented on <a href="<?php echo get_permalink($comment->comment_post_ID); ?>#comment-<?php echo $comment->comment_ID; ?>" rel="external nofollow" title="<?php echo $title; ?>"> <?php echo $title; ?></a>: <?php echo wp_html_excerpt( $comment->comment_content, 45 ); ?> (...)</p></li>
<?php } ?>
</ul>
</code></pre>
<p>Used on comment output divs -</p>
<pre><code>$comment->comment_ID
</code></pre>
<blockquote>
<p>object(WP_User)#345 (7) { ["data"]=> object(stdClass)#344 (10) {
["ID"]=> string(1) "2" ["user_login"]=> string(6) "agent1"
["user_pass"]=> string(34) "$P$BXUSPFSBfmyIrjZ2YUnbIs1GwjkdH50"
["user_nicename"]=> string(6) "agent1" ["user_email"]=> string(19)
"[email protected]" ["user_url"]=> string(0) ""
["user_registered"]=> string(19) "2015-07-25 10:33:27"
["user_activation_key"]=> string(0) "" ["user_status"]=> string(1) "0"
["display_name"]=> string(9) "John Paul" } ["ID"]=> int(2) ["caps"]=>
array(1) { ["agent"]=> bool(true) } ["cap_key"]=> string(15)
"tr_capabilities" ["roles"]=> array(1) { [0]=> string(5) "agent" }
["allcaps"]=> array(2) { ["read"]=> bool(true) ["agent"]=> bool(true)
} ["filter"]=> NULL }</p>
</blockquote>
|
[
{
"answer_id": 200131,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 1,
"selected": false,
"text": "<p>First method, you are missing the second parameter for <code>get_the_author_meta</code>, which is the ID of the author. </p>\n\n<p>Second method, you are using undefined variables.. Check this code, should get you what you want. </p>\n\n<pre><code>// Method 1\n<ul class=\"authpcom\">\n <?php\n $queried_object = get_queried_object();\n $author_email = get_the_author_meta( 'user_email', $queried_object->ID ); \n\n $args = array(\n 'author_email' => $author_email\n );\n $comments = get_comments($args);\n foreach($comments as $comment) :\n echo '<a href=\" ' . get_permalink( $comment->comment_post_ID ) . ' \" rel=\"external nofollow\" title=\" ' . get_the_title( $comment->comment_post_ID ) . ' \">' . get_the_title( $comment->comment_post_ID ) . '</a><br />' . $comment->comment_date . '<br /><li>' . $comment->comment_content . '</li>';\n endforeach;\n ?>\n</ul>\n\n\n// Method 2\n<?php\n $comments = get_comments();\n?>\n<ul id=\"recent_comments\">\n<?php foreach ($comments as $comment) { ?>\n<li>\n <p>\n <strong>\n <?php\n echo get_avatar( $comment->comment_author_email, '45' );\n echo strip_tags($comment->comment_author);\n ?>\n </strong>\n &nbsp;commented on <a href=\"<?php echo get_permalink( $comment->comment_post_ID ); ?>#comment-<?php echo $comment->comment_ID; ?>\" rel=\"external nofollow\" title=\"<?php echo get_the_title( $comment->comment_post_ID ); ?>\"> <?php echo get_the_title( $comment->comment_post_ID ); ?></a>: <?php echo wp_html_excerpt( $comment->comment_content, 45 ); ?> (...)\n </p>\n</li>\n<?php } ?>\n</ul>\n</code></pre>\n\n<p><strong>EDIT:</strong> (09/05/2015) </p>\n\n<pre><code>// Method 1\n<ul class=\"authpcom\">\n <?php\n $authorID = get_queried_object_id();\n $author_email = get_the_author_meta( 'user_email', $authorID ); \n\n $args = array(\n 'user_id' => $authorID,\n );\n $comments = get_comments($args);\n if ( $comments ) {\n foreach($comments as $comment) {\n echo '<li><a href=\"' . get_permalink( $comment->comment_post_ID ) . '\" rel=\"external nofollow\" title=\"' . get_the_title( $comment->comment_post_ID ) . '\">' . get_the_title( $comment->comment_post_ID ) . '</a><br>' . $comment->comment_date . '<br>' . $comment->comment_content . '</li>';\n }\n } else {\n echo '<li>No Comments from this Author</li>';\n }\n ?>\n</ul>\n</code></pre>\n"
},
{
"answer_id": 200344,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 0,
"selected": false,
"text": "<p>You can achieve this using the <a href=\"https://wordpress.org/plugins/ultimate-member/\" rel=\"nofollow\">ultimate member</a> plugin. It seems to be able to do a lot of things with user profiles, but also appears to be suitable to display user's comments on the profile page. </p>\n\n<blockquote>\n <p>Show author posts & comments on user profiles</p>\n</blockquote>\n"
},
{
"answer_id": 200381,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 4,
"selected": true,
"text": "<p>What you need to use here is the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Comment_Query\" rel=\"nofollow noreferrer\">WP_Comment_Query()</a> function. </p>\n\n<p>So on the <code>author.php</code> page, you can easily get the author info and ID as followed:</p>\n\n<pre><code>// get author info\n$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));\n\n// set ID\n$user_id = $curauth->ID;\n</code></pre>\n\n<p>Then we add the user ID in the query arguments array:</p>\n\n<pre><code>$args = array(\n 'user_id' => $user_id, // comments by this user only\n 'status' => 'approve',\n 'post_status' => 'publish',\n 'post_type' => 'post'\n);\n</code></pre>\n\n<p>And finally we hit the arguments in the <code>wp_comment_query()</code>:</p>\n\n<pre><code>// The Query\n$comments_query = new WP_Comment_Query;\n$comments = $comments_query->query( $args );\n\n// Comment Loop\nif ( $comments ) {\n foreach ( $comments as $comment ) {\n echo '<p>' . $comment->comment_content . '</p>';\n }\n} else {\n echo 'No comments found.';\n}\n</code></pre>\n\n<p>As an added <em>bonus</em>, I investigated how pagination works with <code>wp_comment_query()</code> for not long ago and <a href=\"https://wordpress.stackexchange.com/questions/184449/wp-comment-query-pagination-delving-into-the-unknown/184451#184451\">offer a good solution here</a>. It was a little bit of a fiddle-niddle to make it work.</p>\n\n<p>EDIT:</p>\n\n<p>A better way to get the author ID is simply with (props @Pieter):</p>\n\n<pre><code>$user_id = get_queried_object_id();\n</code></pre>\n"
}
] |
2015/08/27
|
[
"https://wordpress.stackexchange.com/questions/199860",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24067/"
] |
I am trying to display authors comments on their profile page (author.php), however both codes I tried seem to display everyone's comments. Also the second code is suppose to link to the specific comment, but instead it does nothing. Also the comments id is already added to the comments output and it prints fine. Any help is greatly appreciated.
```
// Method 1
<ul class="authpcom">
<?php
$author_email = get_the_author_meta( 'user_email' );
$args = array(
'author_email' => $author_email
);
$comments = get_comments($args);
foreach($comments as $comment) :
echo('<a href=" ' . get_permalink($comment->post_ID) . ' " rel="external nofollow" title=" ' . $title . ' ">' .$title . '</a><br />' . $comment->comment_date . '<br /><li>' . $comment->comment_content . '</li>');
endforeach;
?>
</ul>
// Method 2
<?php $comments = get_comments(); ?>
<ul id="recent_comments">
<?php foreach ($comments as $comment) { ?>
<li><p><strong><?php
$title = get_the_title($comment->comment_post_ID);
echo get_avatar( $comment, '45' );
echo strip_tags($comment->comment_author); ?></strong> commented on <a href="<?php echo get_permalink($comment->comment_post_ID); ?>#comment-<?php echo $comment->comment_ID; ?>" rel="external nofollow" title="<?php echo $title; ?>"> <?php echo $title; ?></a>: <?php echo wp_html_excerpt( $comment->comment_content, 45 ); ?> (...)</p></li>
<?php } ?>
</ul>
```
Used on comment output divs -
```
$comment->comment_ID
```
>
> object(WP\_User)#345 (7) { ["data"]=> object(stdClass)#344 (10) {
> ["ID"]=> string(1) "2" ["user\_login"]=> string(6) "agent1"
> ["user\_pass"]=> string(34) "$P$BXUSPFSBfmyIrjZ2YUnbIs1GwjkdH50"
> ["user\_nicename"]=> string(6) "agent1" ["user\_email"]=> string(19)
> "[email protected]" ["user\_url"]=> string(0) ""
> ["user\_registered"]=> string(19) "2015-07-25 10:33:27"
> ["user\_activation\_key"]=> string(0) "" ["user\_status"]=> string(1) "0"
> ["display\_name"]=> string(9) "John Paul" } ["ID"]=> int(2) ["caps"]=>
> array(1) { ["agent"]=> bool(true) } ["cap\_key"]=> string(15)
> "tr\_capabilities" ["roles"]=> array(1) { [0]=> string(5) "agent" }
> ["allcaps"]=> array(2) { ["read"]=> bool(true) ["agent"]=> bool(true)
> } ["filter"]=> NULL }
>
>
>
|
What you need to use here is the [WP\_Comment\_Query()](https://codex.wordpress.org/Class_Reference/WP_Comment_Query) function.
So on the `author.php` page, you can easily get the author info and ID as followed:
```
// get author info
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
// set ID
$user_id = $curauth->ID;
```
Then we add the user ID in the query arguments array:
```
$args = array(
'user_id' => $user_id, // comments by this user only
'status' => 'approve',
'post_status' => 'publish',
'post_type' => 'post'
);
```
And finally we hit the arguments in the `wp_comment_query()`:
```
// The Query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
// Comment Loop
if ( $comments ) {
foreach ( $comments as $comment ) {
echo '<p>' . $comment->comment_content . '</p>';
}
} else {
echo 'No comments found.';
}
```
As an added *bonus*, I investigated how pagination works with `wp_comment_query()` for not long ago and [offer a good solution here](https://wordpress.stackexchange.com/questions/184449/wp-comment-query-pagination-delving-into-the-unknown/184451#184451). It was a little bit of a fiddle-niddle to make it work.
EDIT:
A better way to get the author ID is simply with (props @Pieter):
```
$user_id = get_queried_object_id();
```
|
199,879 |
<p>I am trying to create a couple of custom posts and set a custom taxonomy term to it on plugin activation. I am using the register plugin activation hook to do it. The posts are created properly, but I the post term is not being set. I am using <code>wp_set_object_terms</code> to do it. What could be the possible cause?</p>
<p>My code resembles this:</p>
<pre><code>register_activation_hook( __FILE__, 'insert_latest_books' );
public function insert_latest_books() {
//Get the latest books
$data = new Data_Fetcher();
$latest_books = $data->get_latest_books();
foreach($latest_books as $latest_book) {
//Create a book post for each latest book
$book = [
'post_type' => 'book',
'post_status' => 'publish',
'post_title' => $latest_book->name,
'post_content' => $latest_book->description
];
$book_id = wp_insert_post($book);
//TODO: Not working on plugin activation
wp_set_object_terms($book_id, array('latest'), 'label');
set_book_thumbnail($book_id, $latest_book->name, $latest_book->preview_image_url);
update_post_meta($book_id, 'book_code', $latest_book->embed_code);
update_post_meta($book_id, 'book_pages', $latest_book->length);
}
}
</code></pre>
|
[
{
"answer_id": 199875,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 5,
"selected": true,
"text": "<p>It's the nature of the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\">WordPress template hierarchy</a> - point being, if you <em>don't</em> have a <code>page.php</code>, it will use <code>singular.php</code>, same if you don't have <code>single.php</code>, it will <em>fallback</em> to a template lower in the hierarchy.</p>\n\n<p>Ideal for themes that have the same layout for posts/pages, instead of having duplicate code in each respective template.</p>\n"
},
{
"answer_id": 199880,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": false,
"text": "<p><code>singular.php</code> is basically an extra fallback for all post types, regardless if built-in or custom. It comes in straight after <code>single.php</code> and <code>page.php</code>, so you can omit the latter two templates and just have a <code>singular.php</code> template which will be used by all post types in single view.</p>\n\n<p>How useful it will be and the necessity of it will, just as with any other template, depend on the user/site/requirements. The template hierarchy is built such that, regardless of any page being viewed, you will always just need <code>index.php</code> to display any page. So in short, you can have a fully functional theme with only <code>index.php</code> and <code>style.css</code> in the theme folder. </p>\n\n<p>The templates available in the template hierarchy are just there for convenience, and that goes for <code>singular.php</code> as well. You can use any template in context if you <strong>need</strong> to, but you don't have to use it if you don't need it.</p>\n"
},
{
"answer_id": 201694,
"author": "matthew",
"author_id": 52429,
"author_profile": "https://wordpress.stackexchange.com/users/52429",
"pm_score": 2,
"selected": false,
"text": "<p>The single post template file is used to render a single post. WordPress uses the following path:</p>\n\n<p>1.single-{post-type}.php – First, WordPress looks for a template for the specific post type. For example, post type is product, WordPress would look for single-product.php.</p>\n\n<p>2.single.php – WordPress then falls back to single.php.</p>\n\n<p>3.singular.php – Then it falls back to singular.php.</p>\n\n<p>4.index.php – Finally, as mentioned above, WordPress ultimately falls back to index.php.</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post\" rel=\"nofollow\">https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post</a></p>\n\n<p>The template file used to render a static page (page post-type). Note that unlike other post-types, page is special to WordPress and uses the following patch:</p>\n\n<p>1.custom template file – The page template assigned to the page. See get_page_templates().</p>\n\n<p>2.page-{slug}.php – If the page slug is recent-news, WordPress will look to use page-recent-news.php.</p>\n\n<p>3.page-{id}.php – If the page ID is 6, WordPress will look to use page-6.php.</p>\n\n<p>4.page.php</p>\n\n<p>5.singular.php</p>\n\n<p>6.index.php</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#page\" rel=\"nofollow\">https://developer.wordpress.org/themes/basics/template-hierarchy/#page</a></p>\n"
}
] |
2015/08/27
|
[
"https://wordpress.stackexchange.com/questions/199879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4740/"
] |
I am trying to create a couple of custom posts and set a custom taxonomy term to it on plugin activation. I am using the register plugin activation hook to do it. The posts are created properly, but I the post term is not being set. I am using `wp_set_object_terms` to do it. What could be the possible cause?
My code resembles this:
```
register_activation_hook( __FILE__, 'insert_latest_books' );
public function insert_latest_books() {
//Get the latest books
$data = new Data_Fetcher();
$latest_books = $data->get_latest_books();
foreach($latest_books as $latest_book) {
//Create a book post for each latest book
$book = [
'post_type' => 'book',
'post_status' => 'publish',
'post_title' => $latest_book->name,
'post_content' => $latest_book->description
];
$book_id = wp_insert_post($book);
//TODO: Not working on plugin activation
wp_set_object_terms($book_id, array('latest'), 'label');
set_book_thumbnail($book_id, $latest_book->name, $latest_book->preview_image_url);
update_post_meta($book_id, 'book_code', $latest_book->embed_code);
update_post_meta($book_id, 'book_pages', $latest_book->length);
}
}
```
|
It's the nature of the [WordPress template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) - point being, if you *don't* have a `page.php`, it will use `singular.php`, same if you don't have `single.php`, it will *fallback* to a template lower in the hierarchy.
Ideal for themes that have the same layout for posts/pages, instead of having duplicate code in each respective template.
|
199,887 |
<p>I'm trying to use update_value filter hook of Advanced Custom Fields to write a function that when a user deletes an image from the field it will be deleted from the media library of WP as well. So far i haven't managed to make it work i get lots of errors. I need to check if the value of the field is empty then get the previous value (the image) find the ID and delete the attachment? Any ideas?</p>
<pre><code>//Delete image from acf field
function my_acf_update_value( $value, $post_id, $field )
{
if (empty($value)){
$var = get_field($field, $post_id);
$varid = $var['id'];
wp_delete_attachment( $var, true );
}
// do something else to the $post object via the $post_id
return $value;
}
add_filter('acf/update_value/type=image', 'my_acf_update_value', 10, 3);
</code></pre>
<p>Error:</p>
<blockquote>
<p>Warning: Illegal offset type in isset or empty in
/xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-includes/meta.php
on line 484</p>
<p>Warning: Illegal offset type in isset or empty in
/xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-includes/meta.php
on line 484</p>
<p>Warning: Cannot modify header information - headers already sent by
(output started at
/xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-includes/meta.php:484)
in
/xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-admin/post.php
on line 233</p>
<p>Warning: Cannot modify header information - headers already sent by
(output started at
/xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-includes/meta.php:484)
in
/xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-includes/pluggable.php
on line 1179</p>
</blockquote>
|
[
{
"answer_id": 199907,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": true,
"text": "<p>You're close - couple of things:</p>\n\n<ol>\n<li><code>$field</code> is an array representation of the field, so you need to use <code>$field['name']</code> which is the <em>name</em> of the field.</li>\n<li><code>get_field</code> will format the value unless you set the third argument to false - we want the ID, not the post object/URL (or whatever setting you configured for your field return value)</li>\n<li>Your code won't delete the image if a user <em>replaces</em> it with a new one (only processes if <code>$value</code> is empty)</li>\n</ol>\n\n<p>Here it is revised:</p>\n\n<pre><code>function wpse_83587_delete_image( $value, $post_id, $field ) {\n $old_value = get_field( $field['name'], $post_id, false /* Don't format the value, we want the raw ID */ );\n\n if ( $old_value && ( int ) $old_value !== ( int ) $value )\n wp_delete_attachment( $old_value, true );\n\n return $value;\n}\n\nadd_filter( 'acf/update_value/type=image', 'wpse_83587_delete_image', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 296954,
"author": "fngrl",
"author_id": 138730,
"author_profile": "https://wordpress.stackexchange.com/users/138730",
"pm_score": 0,
"selected": false,
"text": "<p>If anyone needs that for repeater fields, the above solution unfortunately does not work, since when the row numbers change, also the field names in the new value change.</p>\n\n<p>For repeaters we have to catch the file fields earlier, when the repeater-updated hooks gets called. </p>\n\n<p>We then compare the old rows with the new rows and for every file field we find in a row, check whether that file still exists in the new rows.</p>\n\n<pre><code>function pg_update_acf_repeater_field( $new_value, $post_id, $field ) {\n $old_value = get_field( $field['name'], $post_id, false );\n\n // If we changed the repeater fields\n if ( $old_value && ($old_value != $new_value) ) {\n // Go through each row of the old values\n foreach ( $old_value as $row ) {\n // Go through each field of the row and check whether it is a file field\n foreach ( $row as $field_key => $field_value ) {\n // We get the field details of our current field\n $field_data = array_filter( $field['sub_fields'], function( $el ) use ($field_key) {\n return $el['key'] == $field_key;\n });\n\n // If we find a file, we check whether it is still present in the new repeater rows as well\n if ( $field_data && in_array( array_values($field_data)[0]['type'], array('image', 'file')) ) {\n $found = false;\n if ( $new_value ) {\n foreach ( $new_value as $row ) {\n if ( $row[$field_key] == $field_value ) $found = true;\n }\n }\n if ( !$found ) {\n wp_delete_attachment( $field_value );\n }\n }\n }\n }\n }\n return $new_value;\n}\nadd_filter( 'acf/update_value/type=repeater', 'pg_update_acf_repeater_field', 10, 3 );\n</code></pre>\n"
}
] |
2015/08/27
|
[
"https://wordpress.stackexchange.com/questions/199887",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70428/"
] |
I'm trying to use update\_value filter hook of Advanced Custom Fields to write a function that when a user deletes an image from the field it will be deleted from the media library of WP as well. So far i haven't managed to make it work i get lots of errors. I need to check if the value of the field is empty then get the previous value (the image) find the ID and delete the attachment? Any ideas?
```
//Delete image from acf field
function my_acf_update_value( $value, $post_id, $field )
{
if (empty($value)){
$var = get_field($field, $post_id);
$varid = $var['id'];
wp_delete_attachment( $var, true );
}
// do something else to the $post object via the $post_id
return $value;
}
add_filter('acf/update_value/type=image', 'my_acf_update_value', 10, 3);
```
Error:
>
> Warning: Illegal offset type in isset or empty in
> /xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-includes/meta.php
> on line 484
>
>
> Warning: Illegal offset type in isset or empty in
> /xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-includes/meta.php
> on line 484
>
>
> Warning: Cannot modify header information - headers already sent by
> (output started at
> /xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-includes/meta.php:484)
> in
> /xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-admin/post.php
> on line 233
>
>
> Warning: Cannot modify header information - headers already sent by
> (output started at
> /xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-includes/meta.php:484)
> in
> /xxx/xxx/xxx/xxx/xxxxxx/xxxxxxx/xxx.xxxxxxxx.com/html/wp-includes/pluggable.php
> on line 1179
>
>
>
|
You're close - couple of things:
1. `$field` is an array representation of the field, so you need to use `$field['name']` which is the *name* of the field.
2. `get_field` will format the value unless you set the third argument to false - we want the ID, not the post object/URL (or whatever setting you configured for your field return value)
3. Your code won't delete the image if a user *replaces* it with a new one (only processes if `$value` is empty)
Here it is revised:
```
function wpse_83587_delete_image( $value, $post_id, $field ) {
$old_value = get_field( $field['name'], $post_id, false /* Don't format the value, we want the raw ID */ );
if ( $old_value && ( int ) $old_value !== ( int ) $value )
wp_delete_attachment( $old_value, true );
return $value;
}
add_filter( 'acf/update_value/type=image', 'wpse_83587_delete_image', 10, 3 );
```
|
199,898 |
<p>I'm trying to develop a plugin which adds a single line to the .htaccess file generated by WordPress.</p>
<p>The problem is that one of the WP generated lines override my rule, and via the "insert_with_markers()" function, I have not found a way to specify a position so I could prepend my line instead of appending it as currently is happening.</p>
<p>The first line of code is the auto generated WordPress line, and the second one is the one I'd like to have working.</p>
<pre><code>RewriteRule . /dev/index.php [L]
RewriteRule ^article/([/_0-9a-zA-Z-]+)$ http://www.domain.tld/?id=$1 [R=301,L,NC]
</code></pre>
<p>The way I see it there's 2 possibilities here:</p>
<p>A) Somehow specify where the insert_with_markers() places the new line of code, or</p>
<p>B) Modify my RewriteRule to work together with the WordPress generated one.</p>
<p>I hope you can point me a step or two closer to the right path.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 199907,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": true,
"text": "<p>You're close - couple of things:</p>\n\n<ol>\n<li><code>$field</code> is an array representation of the field, so you need to use <code>$field['name']</code> which is the <em>name</em> of the field.</li>\n<li><code>get_field</code> will format the value unless you set the third argument to false - we want the ID, not the post object/URL (or whatever setting you configured for your field return value)</li>\n<li>Your code won't delete the image if a user <em>replaces</em> it with a new one (only processes if <code>$value</code> is empty)</li>\n</ol>\n\n<p>Here it is revised:</p>\n\n<pre><code>function wpse_83587_delete_image( $value, $post_id, $field ) {\n $old_value = get_field( $field['name'], $post_id, false /* Don't format the value, we want the raw ID */ );\n\n if ( $old_value && ( int ) $old_value !== ( int ) $value )\n wp_delete_attachment( $old_value, true );\n\n return $value;\n}\n\nadd_filter( 'acf/update_value/type=image', 'wpse_83587_delete_image', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 296954,
"author": "fngrl",
"author_id": 138730,
"author_profile": "https://wordpress.stackexchange.com/users/138730",
"pm_score": 0,
"selected": false,
"text": "<p>If anyone needs that for repeater fields, the above solution unfortunately does not work, since when the row numbers change, also the field names in the new value change.</p>\n\n<p>For repeaters we have to catch the file fields earlier, when the repeater-updated hooks gets called. </p>\n\n<p>We then compare the old rows with the new rows and for every file field we find in a row, check whether that file still exists in the new rows.</p>\n\n<pre><code>function pg_update_acf_repeater_field( $new_value, $post_id, $field ) {\n $old_value = get_field( $field['name'], $post_id, false );\n\n // If we changed the repeater fields\n if ( $old_value && ($old_value != $new_value) ) {\n // Go through each row of the old values\n foreach ( $old_value as $row ) {\n // Go through each field of the row and check whether it is a file field\n foreach ( $row as $field_key => $field_value ) {\n // We get the field details of our current field\n $field_data = array_filter( $field['sub_fields'], function( $el ) use ($field_key) {\n return $el['key'] == $field_key;\n });\n\n // If we find a file, we check whether it is still present in the new repeater rows as well\n if ( $field_data && in_array( array_values($field_data)[0]['type'], array('image', 'file')) ) {\n $found = false;\n if ( $new_value ) {\n foreach ( $new_value as $row ) {\n if ( $row[$field_key] == $field_value ) $found = true;\n }\n }\n if ( !$found ) {\n wp_delete_attachment( $field_value );\n }\n }\n }\n }\n }\n return $new_value;\n}\nadd_filter( 'acf/update_value/type=repeater', 'pg_update_acf_repeater_field', 10, 3 );\n</code></pre>\n"
}
] |
2015/08/27
|
[
"https://wordpress.stackexchange.com/questions/199898",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78187/"
] |
I'm trying to develop a plugin which adds a single line to the .htaccess file generated by WordPress.
The problem is that one of the WP generated lines override my rule, and via the "insert\_with\_markers()" function, I have not found a way to specify a position so I could prepend my line instead of appending it as currently is happening.
The first line of code is the auto generated WordPress line, and the second one is the one I'd like to have working.
```
RewriteRule . /dev/index.php [L]
RewriteRule ^article/([/_0-9a-zA-Z-]+)$ http://www.domain.tld/?id=$1 [R=301,L,NC]
```
The way I see it there's 2 possibilities here:
A) Somehow specify where the insert\_with\_markers() places the new line of code, or
B) Modify my RewriteRule to work together with the WordPress generated one.
I hope you can point me a step or two closer to the right path.
Thanks!
|
You're close - couple of things:
1. `$field` is an array representation of the field, so you need to use `$field['name']` which is the *name* of the field.
2. `get_field` will format the value unless you set the third argument to false - we want the ID, not the post object/URL (or whatever setting you configured for your field return value)
3. Your code won't delete the image if a user *replaces* it with a new one (only processes if `$value` is empty)
Here it is revised:
```
function wpse_83587_delete_image( $value, $post_id, $field ) {
$old_value = get_field( $field['name'], $post_id, false /* Don't format the value, we want the raw ID */ );
if ( $old_value && ( int ) $old_value !== ( int ) $value )
wp_delete_attachment( $old_value, true );
return $value;
}
add_filter( 'acf/update_value/type=image', 'wpse_83587_delete_image', 10, 3 );
```
|
199,906 |
<p>Following this <a href="https://wordpress.stackexchange.com/questions/9775/how-to-edit-a-user-profile-on-the-front-end">post</a>, I tried to add the code in the template of a genesis child theme to edit user's profile (change the password), using genesis actions (genesis_entry_content, genesis_loop,...), replacing the genesis loop,.. </p>
<p>Unfortunatly it doesn't work properly; the fields are there but I have a lot of errors, principally undefined variables. Now, I don't know how to insert it with genesis, or if there is a better solution ?</p>
|
[
{
"answer_id": 199907,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": true,
"text": "<p>You're close - couple of things:</p>\n\n<ol>\n<li><code>$field</code> is an array representation of the field, so you need to use <code>$field['name']</code> which is the <em>name</em> of the field.</li>\n<li><code>get_field</code> will format the value unless you set the third argument to false - we want the ID, not the post object/URL (or whatever setting you configured for your field return value)</li>\n<li>Your code won't delete the image if a user <em>replaces</em> it with a new one (only processes if <code>$value</code> is empty)</li>\n</ol>\n\n<p>Here it is revised:</p>\n\n<pre><code>function wpse_83587_delete_image( $value, $post_id, $field ) {\n $old_value = get_field( $field['name'], $post_id, false /* Don't format the value, we want the raw ID */ );\n\n if ( $old_value && ( int ) $old_value !== ( int ) $value )\n wp_delete_attachment( $old_value, true );\n\n return $value;\n}\n\nadd_filter( 'acf/update_value/type=image', 'wpse_83587_delete_image', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 296954,
"author": "fngrl",
"author_id": 138730,
"author_profile": "https://wordpress.stackexchange.com/users/138730",
"pm_score": 0,
"selected": false,
"text": "<p>If anyone needs that for repeater fields, the above solution unfortunately does not work, since when the row numbers change, also the field names in the new value change.</p>\n\n<p>For repeaters we have to catch the file fields earlier, when the repeater-updated hooks gets called. </p>\n\n<p>We then compare the old rows with the new rows and for every file field we find in a row, check whether that file still exists in the new rows.</p>\n\n<pre><code>function pg_update_acf_repeater_field( $new_value, $post_id, $field ) {\n $old_value = get_field( $field['name'], $post_id, false );\n\n // If we changed the repeater fields\n if ( $old_value && ($old_value != $new_value) ) {\n // Go through each row of the old values\n foreach ( $old_value as $row ) {\n // Go through each field of the row and check whether it is a file field\n foreach ( $row as $field_key => $field_value ) {\n // We get the field details of our current field\n $field_data = array_filter( $field['sub_fields'], function( $el ) use ($field_key) {\n return $el['key'] == $field_key;\n });\n\n // If we find a file, we check whether it is still present in the new repeater rows as well\n if ( $field_data && in_array( array_values($field_data)[0]['type'], array('image', 'file')) ) {\n $found = false;\n if ( $new_value ) {\n foreach ( $new_value as $row ) {\n if ( $row[$field_key] == $field_value ) $found = true;\n }\n }\n if ( !$found ) {\n wp_delete_attachment( $field_value );\n }\n }\n }\n }\n }\n return $new_value;\n}\nadd_filter( 'acf/update_value/type=repeater', 'pg_update_acf_repeater_field', 10, 3 );\n</code></pre>\n"
}
] |
2015/08/27
|
[
"https://wordpress.stackexchange.com/questions/199906",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75422/"
] |
Following this [post](https://wordpress.stackexchange.com/questions/9775/how-to-edit-a-user-profile-on-the-front-end), I tried to add the code in the template of a genesis child theme to edit user's profile (change the password), using genesis actions (genesis\_entry\_content, genesis\_loop,...), replacing the genesis loop,..
Unfortunatly it doesn't work properly; the fields are there but I have a lot of errors, principally undefined variables. Now, I don't know how to insert it with genesis, or if there is a better solution ?
|
You're close - couple of things:
1. `$field` is an array representation of the field, so you need to use `$field['name']` which is the *name* of the field.
2. `get_field` will format the value unless you set the third argument to false - we want the ID, not the post object/URL (or whatever setting you configured for your field return value)
3. Your code won't delete the image if a user *replaces* it with a new one (only processes if `$value` is empty)
Here it is revised:
```
function wpse_83587_delete_image( $value, $post_id, $field ) {
$old_value = get_field( $field['name'], $post_id, false /* Don't format the value, we want the raw ID */ );
if ( $old_value && ( int ) $old_value !== ( int ) $value )
wp_delete_attachment( $old_value, true );
return $value;
}
add_filter( 'acf/update_value/type=image', 'wpse_83587_delete_image', 10, 3 );
```
|
199,912 |
<p>I have plugin that has the same name as other plugin uploaded to wordpress.org<br>
How can i make it unique so it doesn't share "View Detais" link and auto-update with other plugin uploaded to wordpress.org? Considering that name of my plugin <strong>has to be exactly</strong> name it already has and <strong>cannot</strong> be changed.<br>
I've already tried adding this code to myplugin.php:</p>
<pre><code>add_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );
function filter_plugin_updates( $value ) {
if (!empty($value)) {
unset( $value->response['myplugin/myplugin.php'] );
return $value;
}
}
</code></pre>
<p>And that removes update notification for this plugin <em>but only when it's active</em>, and i need to remove it completely <strong>with</strong> "View Detais" link.<br>
Also my plugin is private and will not ever be in the wordpress repository and will not ever need auto-updation.<br>
Any suggestions? Thanks</p>
|
[
{
"answer_id": 199907,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": true,
"text": "<p>You're close - couple of things:</p>\n\n<ol>\n<li><code>$field</code> is an array representation of the field, so you need to use <code>$field['name']</code> which is the <em>name</em> of the field.</li>\n<li><code>get_field</code> will format the value unless you set the third argument to false - we want the ID, not the post object/URL (or whatever setting you configured for your field return value)</li>\n<li>Your code won't delete the image if a user <em>replaces</em> it with a new one (only processes if <code>$value</code> is empty)</li>\n</ol>\n\n<p>Here it is revised:</p>\n\n<pre><code>function wpse_83587_delete_image( $value, $post_id, $field ) {\n $old_value = get_field( $field['name'], $post_id, false /* Don't format the value, we want the raw ID */ );\n\n if ( $old_value && ( int ) $old_value !== ( int ) $value )\n wp_delete_attachment( $old_value, true );\n\n return $value;\n}\n\nadd_filter( 'acf/update_value/type=image', 'wpse_83587_delete_image', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 296954,
"author": "fngrl",
"author_id": 138730,
"author_profile": "https://wordpress.stackexchange.com/users/138730",
"pm_score": 0,
"selected": false,
"text": "<p>If anyone needs that for repeater fields, the above solution unfortunately does not work, since when the row numbers change, also the field names in the new value change.</p>\n\n<p>For repeaters we have to catch the file fields earlier, when the repeater-updated hooks gets called. </p>\n\n<p>We then compare the old rows with the new rows and for every file field we find in a row, check whether that file still exists in the new rows.</p>\n\n<pre><code>function pg_update_acf_repeater_field( $new_value, $post_id, $field ) {\n $old_value = get_field( $field['name'], $post_id, false );\n\n // If we changed the repeater fields\n if ( $old_value && ($old_value != $new_value) ) {\n // Go through each row of the old values\n foreach ( $old_value as $row ) {\n // Go through each field of the row and check whether it is a file field\n foreach ( $row as $field_key => $field_value ) {\n // We get the field details of our current field\n $field_data = array_filter( $field['sub_fields'], function( $el ) use ($field_key) {\n return $el['key'] == $field_key;\n });\n\n // If we find a file, we check whether it is still present in the new repeater rows as well\n if ( $field_data && in_array( array_values($field_data)[0]['type'], array('image', 'file')) ) {\n $found = false;\n if ( $new_value ) {\n foreach ( $new_value as $row ) {\n if ( $row[$field_key] == $field_value ) $found = true;\n }\n }\n if ( !$found ) {\n wp_delete_attachment( $field_value );\n }\n }\n }\n }\n }\n return $new_value;\n}\nadd_filter( 'acf/update_value/type=repeater', 'pg_update_acf_repeater_field', 10, 3 );\n</code></pre>\n"
}
] |
2015/08/27
|
[
"https://wordpress.stackexchange.com/questions/199912",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78437/"
] |
I have plugin that has the same name as other plugin uploaded to wordpress.org
How can i make it unique so it doesn't share "View Detais" link and auto-update with other plugin uploaded to wordpress.org? Considering that name of my plugin **has to be exactly** name it already has and **cannot** be changed.
I've already tried adding this code to myplugin.php:
```
add_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );
function filter_plugin_updates( $value ) {
if (!empty($value)) {
unset( $value->response['myplugin/myplugin.php'] );
return $value;
}
}
```
And that removes update notification for this plugin *but only when it's active*, and i need to remove it completely **with** "View Detais" link.
Also my plugin is private and will not ever be in the wordpress repository and will not ever need auto-updation.
Any suggestions? Thanks
|
You're close - couple of things:
1. `$field` is an array representation of the field, so you need to use `$field['name']` which is the *name* of the field.
2. `get_field` will format the value unless you set the third argument to false - we want the ID, not the post object/URL (or whatever setting you configured for your field return value)
3. Your code won't delete the image if a user *replaces* it with a new one (only processes if `$value` is empty)
Here it is revised:
```
function wpse_83587_delete_image( $value, $post_id, $field ) {
$old_value = get_field( $field['name'], $post_id, false /* Don't format the value, we want the raw ID */ );
if ( $old_value && ( int ) $old_value !== ( int ) $value )
wp_delete_attachment( $old_value, true );
return $value;
}
add_filter( 'acf/update_value/type=image', 'wpse_83587_delete_image', 10, 3 );
```
|
199,999 |
<p>I am using Bootstrap nav pills with drop-down items as WordPress menu, the menu without drop-down is looking good but when I add nested ul as drop-down the menu not working as expected..</p>
<p>HTML</p>
<pre><code><nav class="navbar navbar-default pull-right" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav nav-pills head-menu">
<li class="current"><a href="index.html">Home</a> </li>
<li><a href="authors.html">Authors</a></li>
<li><a href="catalogue.html">Catalogue</a></li>
<li><a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-expanded="false"> Featured <span class="caret"></span> </a>
<ul class="dropdown-menu" role="menu">
<li><a href="featured-videos.html">Featured Videos</a></li>
<li><a href="featured-author.html">Featured Author</a></li>
</ul>
</li>
<li><a href="media.html">Media</a></li>
<li><a href="team.html">Team</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
</div>
</nav>
</code></pre>
<p>PHP</p>
<pre><code><nav class="navbar navbar-default pull-right" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<?php wp_nav_menu( array( 'theme_location' => 'main-menu', 'items_wrap' => '<ul class="nav nav-pills head-menu">%3$s</ul>') ); ?>
</div>
</div>
</nav>
</code></pre>
<p>Everything is good when there is no drop-down items, how to fix this issue? </p>
|
[
{
"answer_id": 219027,
"author": "Gnana lingam",
"author_id": 89548,
"author_profile": "https://wordpress.stackexchange.com/users/89548",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n/**\n * Class Name: wp_bootstrap_navwalker\n * GitHub URI: https://github.com/twittem/wp-bootstrap-navwalker\n * Description: A custom WordPress nav walker class to implement the Bootstrap 3 navigation style in a custom theme using the WordPress built in menu manager.\n * Version: 2.0.4\n * Author: Edward McIntyre - @twittem\n * License: GPL-2.0+\n * License URI: http://www.gnu.org/licenses/gpl-2.0.txt\n */\nclass wp_bootstrap_navwalker extends Walker_Nav_Menu {\n /**\n * @see Walker::start_lvl()\n * @since 3.0.0\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param int $depth Depth of page. Used for padding.\n */\n public function start_lvl( &$output, $depth = 0, $args = array() ) {\n $indent = str_repeat( \"\\t\", $depth );\n $output .= \"\\n$indent<ul role=\\\"menu\\\" class=\\\" category-list\\\">\\n\";\n }\n /**\n * @see Walker::start_el()\n * @since 3.0.0\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param object $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param int $current_page Menu item ID.\n * @param object $args\n */\n public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n $indent = ( $depth ) ? str_repeat( \"\\t\", $depth ) : '';\n /**\n * Dividers, Headers or Disabled\n * =============================\n * Determine whether the item is a Divider, Header, Disabled or regular\n * menu item. To prevent errors we use the strcasecmp() function to so a\n * comparison that is not case sensitive. The strcasecmp() function returns\n * a 0 if the strings are equal.\n */\n if ( strcasecmp( $item->attr_title, 'divider' ) == 0 && $depth === 1 ) {\n $output .= $indent . '<li role=\"presentation\" class=\"divider\">';\n } else if ( strcasecmp( $item->title, 'divider') == 0 && $depth === 1 ) {\n $output .= $indent . '<li role=\"presentation\" class=\"divider\">';\n } else if ( strcasecmp( $item->attr_title, 'dropdown-header') == 0 && $depth === 1 ) {\n $output .= $indent . '<li role=\"presentation\" class=\"dropdown-header\">' . esc_attr( $item->title );\n } else if ( strcasecmp($item->attr_title, 'disabled' ) == 0 ) {\n $output .= $indent . '<li role=\"presentation\" class=\"disabled\"><a href=\"#\">' . esc_attr( $item->title ) . '</a>';\n } else {\n $class_names = $value = '';\n $classes = empty( $item->classes ) ? array() : (array) $item->classes;\n $classes[] = 'menu-item-' . $item->ID;\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );\n if ( $args->has_children )\n $class_names .= ' cd-library';\n if ( in_array( 'current-menu-item', $classes ) )\n $class_names .= ' active';\n $class_names = $class_names ? ' class=\"' . esc_attr( $class_names ) . '\"' : '';\n $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );\n $id = $id ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n $output .= $indent . '<li' . $id . $value . $class_names .'>';\n $atts = array();\n $atts['title'] = ! empty( $item->title ) ? $item->title : '';\n $atts['target'] = ! empty( $item->target ) ? $item->target : '';\n $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';\n // If item has_children add atts to a.\n if ( $args->has_children && $depth === 0 ) {\n $atts['href'] = '#';\n $atts['data-toggle'] = 'dropdown';\n $atts['class'] = 'dropdown-toggle';\n $atts['aria-haspopup'] = 'true';\n } else {\n $atts['href'] = ! empty( $item->url ) ? $item->url : '';\n }\n $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );\n $attributes = '';\n foreach ( $atts as $attr => $value ) {\n if ( ! empty( $value ) ) {\n $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );\n $attributes .= ' ' . $attr . '=\"' . $value . '\"';\n }\n }\n $item_output = $args->before;\n /*\n * Glyphicons\n * ===========\n * Since the the menu item is NOT a Divider or Header we check the see\n * if there is a value in the attr_title property. If the attr_title\n * property is NOT null we apply it as the class name for the glyphicon.\n */\n if ( ! empty( $item->attr_title ) )\n $item_output .= '<a'. $attributes .'><span class=\"glyphicon ' . esc_attr( $item->attr_title ) . '\"></span>&nbsp;';\n else\n $item_output .= '<a'. $attributes .'>';\n $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;\n $item_output .= ( $args->has_children && 0 === $depth ) ? ' <span class=\"caret\"></span></a>' : '</a>';\n $item_output .= $args->after;\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n }\n }\n /**\n * Traverse elements to create list from elements.\n *\n * Display one element if the element doesn't have any children otherwise,\n * display the element and its children. Will only traverse up to the max\n * depth and no ignore elements under that depth.\n *\n * This method shouldn't be called directly, use the walk() method instead.\n *\n * @see Walker::start_el()\n * @since 2.5.0\n *\n * @param object $element Data object\n * @param array $children_elements List of elements to continue traversing.\n * @param int $max_depth Max depth to traverse.\n * @param int $depth Depth of current element.\n * @param array $args\n * @param string $output Passed by reference. Used to append additional content.\n * @return null Null on failure with no changes to parameters.\n */\n public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {\n if ( ! $element )\n return;\n $id_field = $this->db_fields['id'];\n // Display this element.\n if ( is_object( $args[0] ) )\n $args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] );\n parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );\n }\n /**\n * Menu Fallback\n * =============\n * If this function is assigned to the wp_nav_menu's fallback_cb variable\n * and a manu has not been assigned to the theme location in the WordPress\n * menu manager the function with display nothing to a non-logged in user,\n * and will add a link to the WordPress menu manager if logged in as an admin.\n *\n * @param array $args passed from the wp_nav_menu function.\n *\n */\n public static function fallback( $args ) {\n if ( current_user_can( 'manage_options' ) ) {\n extract( $args );\n $fb_output = null;\n if ( $container ) {\n $fb_output = '<' . $container;\n if ( $container_id )\n $fb_output .= ' id=\"' . $container_id . '\"';\n if ( $container_class )\n $fb_output .= ' class=\"' . $container_class . '\"';\n $fb_output .= '>';\n }\n $fb_output .= '<ul';\n if ( $menu_id )\n $fb_output .= ' id=\"' . $menu_id . '\"';\n if ( $menu_class )\n $fb_output .= ' class=\"' . $menu_class . '\"';\n $fb_output .= '>';\n $fb_output .= '<li><a href=\"' . admin_url( 'nav-menus.php' ) . '\">Add a menu</a></li>';\n $fb_output .= '</ul>';\n if ( $container )\n $fb_output .= '</' . $container . '>';\n echo $fb_output;\n }\n }\n}\n\n//Use theme\n <?php wp_nav_menu( array(\n 'menu' => 'main-nav',\n 'theme_location' => 'main-nav',\n 'depth' => 2,\n 'container' => false,\n 'menu_class' => 'main-navigation',\n 'fallback_cb' => 'wp_bootstrap_navwalker::fallback',\n 'walker' => new wp_bootstrap_navwalker())\n ); ?>\n</code></pre>\n"
},
{
"answer_id": 290887,
"author": "maverick",
"author_id": 132953,
"author_profile": "https://wordpress.stackexchange.com/users/132953",
"pm_score": 1,
"selected": false,
"text": "<p>I ran into similar problem when I created a bootstrap navigation menu and dropdown links were all showing up at once. \nI used the following steps to correct the issue:</p>\n\n<ol>\n<li><p>download navwalker from github repo link: <a href=\"https://github.com/wp-bootstrap/wp-bootstrap-navwalker\" rel=\"nofollow noreferrer\">https://github.com/wp-bootstrap/wp-bootstrap-navwalker</a></p></li>\n<li><p>put this file in the root folder of the theme and in the functions.php file\nuse<code>require_once get_template_directory() . '/wp-bootstrap-navwalker.php';</code></p></li>\n<li><p>finally you'll have to add following parameters:</p>\n\n<pre><code>$defaults = array(\n 'container' => false,\n 'theme_location' => 'primary-menu',\n 'menu_class' => 'nav navbar-nav navbar-right',\n 'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',\n 'walker' => new WP_Bootstrap_Navwalker(),\n);\nwp_nav_menu($defaults);\n</code></pre></li>\n</ol>\n\n<p>especially last two parameters to your <code>wp_nav_menu()</code> function.</p>\n\n<p>I hope it helps</p>\n"
},
{
"answer_id": 298358,
"author": "Shashi Kant Singh",
"author_id": 138228,
"author_profile": "https://wordpress.stackexchange.com/users/138228",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n\n/**\n * Bootstrap NavWalker\n * Class Name: Bootstrap_NavWalker\n * Author: Bishal Napit\n * Author URI: https://napitwptech.com/\n * GitHub URI: https://github.com/mebishalnapit/bootstrap-navwalker/\n * Description: A custom WordPress nav walker class to implement the Bootstrap 4 navigation style in a custom WordPress\n * Bootstrap based theme using the WordPress built in menu manager.\n * License: GNU General Public License v3 or later\n * License URI: http://www.gnu.org/licenses/gpl-3.0.html\n */\nclass Bootstrap_NavWalker extends Walker_Nav_Menu {\n\n // Create the $current_menu_id_bootstrap variable for generating the current menu id\n protected $current_menu_id_bootstrap;\n\n /**\n * Starts the list before the elements are added.\n *\n * @since 3.0.0\n * @see Walker::start_lvl()\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param int $depth Depth of menu item. Used for padding.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n */\n public function start_lvl( &$output, $depth = 0, $args = array() ) {\n // Use the current menu id generated via start_el()\n $current_menu_id = $this->current_menu_id_bootstrap;\n\n // Assign the dynamic id for use inside the dropdown menu, ie, sub-menu for Bootstrap\n $id = 'aria-labelledby=\"navbar-dropdown-menu-link-' . $current_menu_id->ID . '\"';\n\n if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {\n $t = '';\n $n = '';\n } else {\n $t = \"\\t\";\n $n = \"\\n\";\n }\n\n $indent = str_repeat( $t, $depth );\n\n /**\n * Add the classes for the dropdown menu in WordPress\n *\n * 1. For WordPress default: '.sub-menu'\n * 2. For Bootstrap Sub-Menu: '.dropdown-menu'\n */\n $classes = array( 'sub-menu', 'dropdown-menu' );\n\n /**\n * Filters the CSS class(es) applied to a menu list element.\n *\n * @since 4.8.0\n *\n * @param array $classes The CSS classes that are applied to the menu `<ul>` element.\n * @param stdClass $args An object of `wp_nav_menu()` arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $class_names = join( ' ', apply_filters( 'nav_menu_submenu_css_class', $classes, $args, $depth ) );\n $class_names = $class_names ? ' class=\"' . esc_attr( $class_names ) . '\"' : '';\n\n /**\n * Change <ul> to <div> for Bootstrap Navigation\n * Add the current menu id for the sub-menu toggle feature for Bootstrap\n */\n $output .= \"{$n}{$indent}<div $class_names $id>{$n}\";\n }\n\n /**\n * Ends the list of after the elements are added.\n *\n * @since 3.0.0\n * @see Walker::end_lvl()\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param int $depth Depth of menu item. Used for padding.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n */\n public function end_lvl( &$output, $depth = 0, $args = array() ) {\n if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {\n $t = '';\n $n = '';\n } else {\n $t = \"\\t\";\n $n = \"\\n\";\n }\n\n $indent = str_repeat( $t, $depth );\n\n /**\n * Change </ul> to </div> for Bootstrap Navigation\n */\n $output .= \"$indent</div>{$n}\";\n }\n\n /**\n * Starts the element output.\n *\n * @since 3.0.0\n * @since 4.4.0 The {@see 'nav_menu_item_args'} filter was added.\n * @see Walker::start_el()\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param WP_Post $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $id Current item ID.\n */\n public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n // Find the current menu item id to be used for start_lvl()\n $this->current_menu_id_bootstrap = $item;\n\n if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {\n $t = '';\n $n = '';\n } else {\n $t = \"\\t\";\n $n = \"\\n\";\n }\n\n $indent = ( $depth ) ? str_repeat( $t, $depth ) : '';\n\n $classes = empty( $item->classes ) ? array() : ( array ) $item->classes;\n $classes[] = 'menu-item-' . $item->ID;\n\n /**\n * Add class '.nav-item' inside <li> tag for Bootstrap\n */\n $classes[] = 'nav-item';\n\n /**\n * Add class '.active' inside <li> tag for Bootstrap active menu as well as for the parent menu, which have the active sub-menu\n */\n if ( in_array( 'current-menu-item', $classes ) || in_array( 'current-menu-parent', $classes ) ) {\n $classes[] = 'active';\n }\n\n /**\n * Add class '.dropdown' inside <li> tag for Bootstrap dropdown menu, ie, <li> having sub-menu\n */\n if ( in_array( 'menu-item-has-children', $classes ) ) {\n $classes[] = 'dropdown';\n }\n\n /**\n * Filters the arguments for a single nav menu item.\n *\n * @since 4.4.0\n *\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param WP_Post $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );\n\n /**\n * Filters the CSS class(es) applied to a menu item's list item element.\n *\n * @since 3.0.0\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param array $classes The CSS classes that are applied to the menu item's `<li>` element.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );\n $class_names = $class_names ? ' class=\"' . esc_attr( $class_names ) . '\"' : '';\n\n /**\n * Filters the ID applied to a menu item's list item element.\n *\n * @since 3.0.1\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param string $menu_id The ID that is applied to the menu item's `<li>` element.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth );\n $id = $id ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n\n /**\n * <li> is required for parent menu only in Bootstrap\n */\n if ( $depth === 0 ) {\n $output .= $indent . '<li' . $id . $class_names . '>';\n }\n\n $atts = array();\n $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';\n $atts['target'] = ! empty( $item->target ) ? $item->target : '';\n $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';\n $atts['href'] = ! empty( $item->url ) ? $item->url : '';\n\n /**\n * Add '.nav-link' class for <a> in parent menu for Bootstrap\n */\n if ( $depth === 0 ) {\n $atts['class'] = 'nav-link';\n }\n\n /**\n * Add the attributes for <a> in parent menu\n *\n * 1. Add '.dropdown-toggle' class for <a> in parent menu if it has sub-menu as required for Bootstrap\n * 2. Add '.dropdown' as 'data-toggle' attribute in <a> in parent menu if it has sub-menu as required for Bootstrap\n * 3. Add the current menu id attribute to indicate the exact menu to toggle for set in sub-menu div\n * 4. Add the attribute of 'true' for 'aria-haspopup' in parent menu to indicate it has sub-menus\n * 5. Add the attribute of 'false' for 'aria-expanded' in parent menu to indicate the sub-menus is hidden by default\n * 6. Add the '#' link in the <a> tag in the parent menu if it has sub-menu as required for Bootstrap\n */\n if ( $depth === 0 && in_array( 'menu-item-has-children', $classes ) ) {\n $atts['class'] .= ' dropdown-toggle';\n $atts['data-toggle'] = 'dropdown';\n $atts['id'] = 'navbar-dropdown-menu-link-' . $item->ID;\n $atts['aria-haspopup'] = \"true\";\n $atts['aria-expanded'] = \"false\";\n $atts['href'] = '#';\n }\n\n /**\n * Add the attributes for <a> in sub-menu\n * 1. Add '.dropdown-item' class for <a> inside sub-menu for Bootstrap\n * 2. Add the current menu id attribute if you want to style the menu differently\n */\n if ( $depth > 0 ) {\n $atts['class'] = 'dropdown-item';\n $atts['id'] = 'menu-item-' . $item->ID;\n }\n\n /**\n * Add '.active' class inside <a> in sub-menu for Bootstrap\n */\n if ( in_array( 'current-menu-item', $item->classes ) ) {\n $atts['class'] .= ' active';\n }\n\n /**\n * Add '.disabled' class for <a> in menu for Bootstrap disabled class\n */\n if ( in_array( 'disabled', $item->classes ) ) {\n $atts['class'] .= ' disabled';\n }\n\n /**\n * Filters the HTML attributes applied to a menu item's anchor element.\n *\n * @since 3.6.0\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param array $atts {\n * The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.\n *\n * @type string $title Title attribute.\n * @type string $target Target attribute.\n * @type string $rel The rel attribute.\n * @type string $href The href attribute.\n * }\n *\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );\n\n $attributes = '';\n foreach ( $atts as $attr => $value ) {\n if ( ! empty( $value ) ) {\n $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );\n\n /**\n * If '.disabled' class is added to the menu, add the url of '#' in it\n */\n if ( in_array( 'disabled', $item->classes ) ) {\n $value = ( 'href' === $attr ) ? esc_url( '#' ) : esc_attr( $value );\n }\n\n $attributes .= ' ' . $attr . '=\"' . $value . '\"';\n }\n }\n\n /** This filter is documented in wp-includes/post-template.php */\n $title = apply_filters( 'the_title', $item->title, $item->ID );\n\n /**\n * Filters a menu item's title.\n *\n * @since 4.4.0\n *\n * @param string $title The menu item's title.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );\n\n $item_output = $args->before;\n $item_output .= '<a' . $attributes . '>';\n $item_output .= $args->link_before . $title . $args->link_after;\n $item_output .= '</a>';\n $item_output .= $args->after;\n\n /**\n * Filters a menu item's starting output.\n * The menu item's starting output only includes `$args->before`, the opening `<a>`,\n * the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is\n * no filter for modifying the opening and closing `<li>` for a menu item.\n *\n * @since 3.0.0\n *\n * @param string $item_output The menu item's starting HTML output.\n * @param WP_Post $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n */\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n }\n\n /**\n * Ends the element output, if needed.\n *\n * @since 3.0.0\n * @see Walker::end_el()\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param WP_Post $item Page data object. Not used.\n * @param int $depth Depth of page. Not Used.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n */\n public function end_el( &$output, $item, $depth = 0, $args = array() ) {\n if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {\n $t = '';\n $n = '';\n } else {\n $t = \"\\t\";\n $n = \"\\n\";\n }\n\n /**\n * <li> is required for parent menu only in Bootstrap\n */\n if ( $depth === 0 ) {\n $output .= \"</li>{$n}\";\n }\n }\n\n /**\n * Fallback menu\n * If you assign the fallback menu for your custom menu setup via wp_nav_menu function, then, this function will be\n * rendered if no menu is assigned to that menu location. You need to assign it via 'fallback_cb' array. Also, this\n * will be only rendered to the logged in users pointing them to the menu manager url.\n *\n * @param $args Arrays passed from the wp_nav_menu function\n */\n public static function fallback( $args ) {\n if ( current_user_can( 'edit_theme_options' ) ) {\n $container = $args['container'];\n $container_id = $args['container_id'];\n $container_class = $args['container_class'];\n $menu_class = $args['menu_class'];\n $menu_id = $args['menu_id'];\n\n // If there is container render it\n if ( $container ) {\n echo '<' . esc_attr( $container );\n\n // If container id is set render it\n if ( $container_id ) {\n echo ' id=\"' . esc_attr( $container_id ) . '\"';\n }\n\n // If container class is set render it\n if ( $container_class ) {\n echo ' class=\"' . esc_attr( $container_class ) . '\"';\n }\n\n echo '>';\n }\n\n // Default wrapper for menu is <ul>\n echo '<ul';\n\n // If menu id has been set render it\n if ( $menu_id ) {\n echo ' id=\"' . esc_attr( $menu_id ) . '\"';\n }\n\n // If menu class has been set render it\n if ( $menu_class ) {\n echo ' class=\"' . esc_attr( $menu_class ) . '\"';\n }\n\n // Close <ul> div wrapper for menu\n echo '>';\n\n // Display the link to Add New Menu\n echo '<li class=\"nav-item active\"><a class=\"nav-link\" href=\"' . esc_url( admin_url( 'nav-menus.php' ) ) . '\">';\n esc_html_e( 'Add a menu', 'theme-textdomain' );\n echo '</a></li>';\n\n // Close the main <ul>\n echo '</ul>';\n\n // Close the main container div\n if ( $container ) {\n echo '</' . esc_attr( $container ) . '>';\n }\n\n }\n }\n\n}\n</code></pre>\n"
}
] |
2015/08/28
|
[
"https://wordpress.stackexchange.com/questions/199999",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78442/"
] |
I am using Bootstrap nav pills with drop-down items as WordPress menu, the menu without drop-down is looking good but when I add nested ul as drop-down the menu not working as expected..
HTML
```
<nav class="navbar navbar-default pull-right" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav nav-pills head-menu">
<li class="current"><a href="index.html">Home</a> </li>
<li><a href="authors.html">Authors</a></li>
<li><a href="catalogue.html">Catalogue</a></li>
<li><a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-expanded="false"> Featured <span class="caret"></span> </a>
<ul class="dropdown-menu" role="menu">
<li><a href="featured-videos.html">Featured Videos</a></li>
<li><a href="featured-author.html">Featured Author</a></li>
</ul>
</li>
<li><a href="media.html">Media</a></li>
<li><a href="team.html">Team</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
</div>
</nav>
```
PHP
```
<nav class="navbar navbar-default pull-right" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<?php wp_nav_menu( array( 'theme_location' => 'main-menu', 'items_wrap' => '<ul class="nav nav-pills head-menu">%3$s</ul>') ); ?>
</div>
</div>
</nav>
```
Everything is good when there is no drop-down items, how to fix this issue?
|
I ran into similar problem when I created a bootstrap navigation menu and dropdown links were all showing up at once.
I used the following steps to correct the issue:
1. download navwalker from github repo link: <https://github.com/wp-bootstrap/wp-bootstrap-navwalker>
2. put this file in the root folder of the theme and in the functions.php file
use`require_once get_template_directory() . '/wp-bootstrap-navwalker.php';`
3. finally you'll have to add following parameters:
```
$defaults = array(
'container' => false,
'theme_location' => 'primary-menu',
'menu_class' => 'nav navbar-nav navbar-right',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker(),
);
wp_nav_menu($defaults);
```
especially last two parameters to your `wp_nav_menu()` function.
I hope it helps
|
200,049 |
<p>There are many posts that seem to strike around this area, but I'm more and more confused by each one I read.</p>
<p>I have a page that shows the "Terms of Service" (id = 1086). I would like to display the content of that page inside a template (signup.php) on another page.</p>
<p>I'm running latest version (4.3). I'm confused by where to put which bit of code. (functions.php vs right in the template etc...)</p>
<p>How can I show the content of my Terms of Service page on my signup template?</p>
<p>EDIT:
Note the change to the post id.</p>
<p>Using @terminator's advice here is the code that I have on my signup.php page:</p>
<pre><code><div id="termsOfService">
<?php $my_postid = 1086;//This is page id or post id
$content_post = get_post($my_postid);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
echo $content; ?>
</div> <!-- termsOfService -->
</code></pre>
<p>This returns an empty string</p>
<p>Here is the permalink and shortlink</p>
<p><a href="https://i.stack.imgur.com/KxTyY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KxTyY.jpg" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 200051,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 1,
"selected": false,
"text": "<p>It should work</p>\n\n<pre><code><?php\n$my_postid = 1772;//This is page id or post id\n$content_post = get_post($my_postid);\n$content = $content_post->post_content;\n$content = apply_filters('the_content', $content);\n$content = str_replace(']]>', ']]&gt;', $content);\necho $content;\n?>\n</code></pre>\n"
},
{
"answer_id": 200503,
"author": "crthompson",
"author_id": 71680,
"author_profile": "https://wordpress.stackexchange.com/users/71680",
"pm_score": 1,
"selected": true,
"text": "<p>The code that worked for me was the following:</p>\n\n<pre><code><? $the_query = new WP_Query( 'page_id=1086' );\n while ( $the_query->have_posts() ) :\n $the_query->the_post();\n the_title();\n the_content();\n endwhile;\n wp_reset_postdata();\n ?>\n</code></pre>\n\n<p>I found this on a <a href=\"https://wordpress.org/support/topic/showing-one-pages-content-on-another-page\" rel=\"nofollow\">thread here</a></p>\n"
}
] |
2015/08/28
|
[
"https://wordpress.stackexchange.com/questions/200049",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71680/"
] |
There are many posts that seem to strike around this area, but I'm more and more confused by each one I read.
I have a page that shows the "Terms of Service" (id = 1086). I would like to display the content of that page inside a template (signup.php) on another page.
I'm running latest version (4.3). I'm confused by where to put which bit of code. (functions.php vs right in the template etc...)
How can I show the content of my Terms of Service page on my signup template?
EDIT:
Note the change to the post id.
Using @terminator's advice here is the code that I have on my signup.php page:
```
<div id="termsOfService">
<?php $my_postid = 1086;//This is page id or post id
$content_post = get_post($my_postid);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content; ?>
</div> <!-- termsOfService -->
```
This returns an empty string
Here is the permalink and shortlink
[](https://i.stack.imgur.com/KxTyY.jpg)
|
The code that worked for me was the following:
```
<? $the_query = new WP_Query( 'page_id=1086' );
while ( $the_query->have_posts() ) :
$the_query->the_post();
the_title();
the_content();
endwhile;
wp_reset_postdata();
?>
```
I found this on a [thread here](https://wordpress.org/support/topic/showing-one-pages-content-on-another-page)
|
200,053 |
<p>I migrated a WordPress 4.3 site from Register.com to MediaTemple today and found that the forced SSL is causing issues for the staging URL.</p>
<p>In order to try again I have (on the live Register.com site)</p>
<ul>
<li>Disabled plugin 'WordPress HTTPS'</li>
<li>Removed <code>define( 'FORCE_SSL_ADMIN', true );</code> from wp-config</li>
<li>In General Settings replaced https w http for URLs and saved</li>
<li>Saved permalinks just in case</li>
<li>verified that .htaccess is not redirecting to https via mod_rewrite</li>
</ul>
<p>Tried logging out and accessing site and still get redirected from http to https.</p>
<p>Assuming my predecessor has not done anything truly crazy what am I missing there? Where should I look?</p>
|
[
{
"answer_id": 200056,
"author": "jerrygarciuh",
"author_id": 12414,
"author_profile": "https://wordpress.stackexchange.com/users/12414",
"pm_score": 2,
"selected": true,
"text": "<p>In the active theme I found the redirection in header.php</p>\n\n<p>Once commented out the issue was resolved.</p>\n\n<pre><code>if($_SERVER[\"HTTPS\"] != \"on\")\n{\n header(\"Location: https://\" . $_SERVER[\"HTTP_HOST\"] . $_SERVER[\"REQUEST_URI\"]);\n exit();\n}\n</code></pre>\n"
},
{
"answer_id": 332790,
"author": "butterchikita",
"author_id": 163978,
"author_profile": "https://wordpress.stackexchange.com/users/163978",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same issue after a migration on staging local environnent, I resolved it by emptying the cache with a hard refresh. </p>\n"
}
] |
2015/08/28
|
[
"https://wordpress.stackexchange.com/questions/200053",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12414/"
] |
I migrated a WordPress 4.3 site from Register.com to MediaTemple today and found that the forced SSL is causing issues for the staging URL.
In order to try again I have (on the live Register.com site)
* Disabled plugin 'WordPress HTTPS'
* Removed `define( 'FORCE_SSL_ADMIN', true );` from wp-config
* In General Settings replaced https w http for URLs and saved
* Saved permalinks just in case
* verified that .htaccess is not redirecting to https via mod\_rewrite
Tried logging out and accessing site and still get redirected from http to https.
Assuming my predecessor has not done anything truly crazy what am I missing there? Where should I look?
|
In the active theme I found the redirection in header.php
Once commented out the issue was resolved.
```
if($_SERVER["HTTPS"] != "on")
{
header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
exit();
}
```
|
200,082 |
<p>I'm trying to load a stylesheet for a particular admin submenu page. The code below is what I came up with after looking up <code>admin_enqueue_scripts</code> in the codex:</p>
<pre><code>function my_function($hook) {
if ( 'themes.php?page=page-name' != $hook ) {
return;
}
wp_enqueue_style( 'custom-style', get_template_directory_uri() . 'custom-page/style.css' );
}
add_action( 'admin_enqueue_scripts', 'my_function' );
</code></pre>
<p>As you can see I'm trying to load it on a submenu page. Not just on 'themes.php', but on a custom page I've created called 'page-name'. The code works if <code>'themes.php' != $hook</code> and loads on 'themes.php'. <code>'themes.php?page=page-name' != $hook</code> however does not load on 'themes.php?page=page-name'.</p>
<p>Any idea on how to go about this? Thanks in advance!</p>
<p>EDIT: This is how the page is declared</p>
<pre><code>function my_function_settings_page_init() {
$theme_data = wp_get_theme();
$settings_page = add_theme_page( $theme_data->get( 'Name' ). ' About', $theme_data->get( 'Name' ). ' About', 'edit_theme_options', 'page-name', 'my_function_settings_page' );
add_action( "load-{$settings_page}", 'my_function_load_settings_page' );
}
function my_function_load_settings_page() {
$_POST["my-function-settings-submit"] = '';
if ( $_POST["my-function-settings-submit"] == 'Y' ) {
check_admin_referer( "my-function-settings-page" );
my_function_save_theme_settings();
$url_parameters = isset($_GET['tab'])? 'updated=true&tab='.$_GET['tab'] : 'updated=true';
wp_redirect(admin_url('themes.php?page=page-name&'.$url_parameters));
exit;
}
}
</code></pre>
|
[
{
"answer_id": 200086,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>if you have declared the page with <code>add_theme_page(...</code>, you can add the stylesheet in the hook <code>load-appearance_page_page-name</code> or <code>admin_print_styles-appearance_page_page-name</code>.</p>\n\n<p>for information, these are some hook which are fired when you load the page (it's not the whole list but the most interesting for your question)</p>\n\n<pre><code>plugins_loaded\ninit\nadmin_init\ncurrent_screen\nload-appearance_page_page-name\nadmin_enqueue_scripts\nadmin_print_styles-appearance_page_page-name\nadmin_print_styles\nadmin_print_scripts-appearance_page_page-name\nadmin_print_scripts\nwp_print_scripts\nadmin_head-appearance_page_page-name\nadmin_head\nadmin_notices\nall_admin_notices\nappearance_page_page-name\nin_admin_footer\nadmin_footer-appearance_page_page-name\n</code></pre>\n\n<p>they are in the order that they append</p>\n"
},
{
"answer_id": 200090,
"author": "kathrineh",
"author_id": 18937,
"author_profile": "https://wordpress.stackexchange.com/users/18937",
"pm_score": 2,
"selected": true,
"text": "<p>Ok, I figured it out: If it's a submenu page, the <code>$hook</code> looks like this: <code>appearance_page_page-name</code> instead of going by URL. So the complete code would be this:</p>\n\n<pre><code>function my_function($hook) {\n if ( 'appearance_page_page-name' != $hook ) {\n return;\n }\n wp_enqueue_style( 'custom-style', get_template_directory_uri() . 'custom-page/style.css' );\n}\nadd_action( 'admin_enqueue_scripts', 'my_function' );\n</code></pre>\n"
}
] |
2015/08/29
|
[
"https://wordpress.stackexchange.com/questions/200082",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18937/"
] |
I'm trying to load a stylesheet for a particular admin submenu page. The code below is what I came up with after looking up `admin_enqueue_scripts` in the codex:
```
function my_function($hook) {
if ( 'themes.php?page=page-name' != $hook ) {
return;
}
wp_enqueue_style( 'custom-style', get_template_directory_uri() . 'custom-page/style.css' );
}
add_action( 'admin_enqueue_scripts', 'my_function' );
```
As you can see I'm trying to load it on a submenu page. Not just on 'themes.php', but on a custom page I've created called 'page-name'. The code works if `'themes.php' != $hook` and loads on 'themes.php'. `'themes.php?page=page-name' != $hook` however does not load on 'themes.php?page=page-name'.
Any idea on how to go about this? Thanks in advance!
EDIT: This is how the page is declared
```
function my_function_settings_page_init() {
$theme_data = wp_get_theme();
$settings_page = add_theme_page( $theme_data->get( 'Name' ). ' About', $theme_data->get( 'Name' ). ' About', 'edit_theme_options', 'page-name', 'my_function_settings_page' );
add_action( "load-{$settings_page}", 'my_function_load_settings_page' );
}
function my_function_load_settings_page() {
$_POST["my-function-settings-submit"] = '';
if ( $_POST["my-function-settings-submit"] == 'Y' ) {
check_admin_referer( "my-function-settings-page" );
my_function_save_theme_settings();
$url_parameters = isset($_GET['tab'])? 'updated=true&tab='.$_GET['tab'] : 'updated=true';
wp_redirect(admin_url('themes.php?page=page-name&'.$url_parameters));
exit;
}
}
```
|
Ok, I figured it out: If it's a submenu page, the `$hook` looks like this: `appearance_page_page-name` instead of going by URL. So the complete code would be this:
```
function my_function($hook) {
if ( 'appearance_page_page-name' != $hook ) {
return;
}
wp_enqueue_style( 'custom-style', get_template_directory_uri() . 'custom-page/style.css' );
}
add_action( 'admin_enqueue_scripts', 'my_function' );
```
|
200,093 |
<p>I have a custom page template that looks like this:</p>
<pre><code><?php if( is_user_logged_in() ): ?>
<?php get_header(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php thinkup_input_nav( 'nav-below' ); ?>
<?php thinkup_input_allowcomments(); ?>
<?php endwhile; wp_reset_query(); ?>
<?php get_footer(); ?>
<?php else:
wp_die('Sorry, you must first <a href="/wp-login.php">log in</a> to view this page. You can <a href="/wp-login.php?action=register">register free here</a>.');
endif; ?>
</code></pre>
<p>Now, when I browse to the page that uses this page template, I'm asked to login. After the login, I'm redirected to the Wordpress admin panel. Browsing manually to the page only shows the same login again.</p>
<ul>
<li>How can I ensure that is_user_logged_in() detects that I'm logged in; and</li>
<li>That I'm redirected to the page itself.</li>
</ul>
<p>Thanks!</p>
|
[
{
"answer_id": 200117,
"author": "Jennifer M.",
"author_id": 78564,
"author_profile": "https://wordpress.stackexchange.com/users/78564",
"pm_score": 0,
"selected": false,
"text": "<p>Try logging in with an account that's NOT an admin account. I think that's just a quirk of an admin account...it assumes you want to go to the control panel.</p>\n"
},
{
"answer_id": 200484,
"author": "Paulie-C",
"author_id": 78546,
"author_profile": "https://wordpress.stackexchange.com/users/78546",
"pm_score": 3,
"selected": true,
"text": "<p>By removing the ADMIN SSL login in <code>wp-config.php</code>, I solved this.</p>\n\n<p>So, remove this:</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', true);\n</code></pre>\n\n<p>Read more about this feature <a href=\"https://codex.wordpress.org/Administration_Over_SSL\" rel=\"nofollow\">here</a></p>\n"
}
] |
2015/08/29
|
[
"https://wordpress.stackexchange.com/questions/200093",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78546/"
] |
I have a custom page template that looks like this:
```
<?php if( is_user_logged_in() ): ?>
<?php get_header(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php thinkup_input_nav( 'nav-below' ); ?>
<?php thinkup_input_allowcomments(); ?>
<?php endwhile; wp_reset_query(); ?>
<?php get_footer(); ?>
<?php else:
wp_die('Sorry, you must first <a href="/wp-login.php">log in</a> to view this page. You can <a href="/wp-login.php?action=register">register free here</a>.');
endif; ?>
```
Now, when I browse to the page that uses this page template, I'm asked to login. After the login, I'm redirected to the Wordpress admin panel. Browsing manually to the page only shows the same login again.
* How can I ensure that is\_user\_logged\_in() detects that I'm logged in; and
* That I'm redirected to the page itself.
Thanks!
|
By removing the ADMIN SSL login in `wp-config.php`, I solved this.
So, remove this:
```
define('FORCE_SSL_ADMIN', true);
```
Read more about this feature [here](https://codex.wordpress.org/Administration_Over_SSL)
|
200,096 |
<p>Before to report this to wordpress I would like to know if it's just me or it's actually a bug. I noticed also another user that asked on the wordpress forum but he hadn't an answer for that: <a href="https://wordpress.org/support/topic/admin-left-menu-overlap" rel="nofollow noreferrer">https://wordpress.org/support/topic/admin-left-menu-overlap</a></p>
<p>And the same is here:
<a href="https://i.stack.imgur.com/SVEhY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SVEhY.jpg" alt="admin sidebar overlapping"></a></p>
<p>It happens almost every time I move the cursor above the panel and it seems to give this problem only in Chrome but I couldn't try it in other browser except for Edge where it seems to work fine.</p>
<p>My environment information is:<br>
OS: Windows 10 64bit<br>
Browser: 45.0.2454.78 beta-m (64-bit) extensions all deactivated</p>
|
[
{
"answer_id": 200117,
"author": "Jennifer M.",
"author_id": 78564,
"author_profile": "https://wordpress.stackexchange.com/users/78564",
"pm_score": 0,
"selected": false,
"text": "<p>Try logging in with an account that's NOT an admin account. I think that's just a quirk of an admin account...it assumes you want to go to the control panel.</p>\n"
},
{
"answer_id": 200484,
"author": "Paulie-C",
"author_id": 78546,
"author_profile": "https://wordpress.stackexchange.com/users/78546",
"pm_score": 3,
"selected": true,
"text": "<p>By removing the ADMIN SSL login in <code>wp-config.php</code>, I solved this.</p>\n\n<p>So, remove this:</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', true);\n</code></pre>\n\n<p>Read more about this feature <a href=\"https://codex.wordpress.org/Administration_Over_SSL\" rel=\"nofollow\">here</a></p>\n"
}
] |
2015/08/29
|
[
"https://wordpress.stackexchange.com/questions/200096",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78388/"
] |
Before to report this to wordpress I would like to know if it's just me or it's actually a bug. I noticed also another user that asked on the wordpress forum but he hadn't an answer for that: <https://wordpress.org/support/topic/admin-left-menu-overlap>
And the same is here:
[](https://i.stack.imgur.com/SVEhY.jpg)
It happens almost every time I move the cursor above the panel and it seems to give this problem only in Chrome but I couldn't try it in other browser except for Edge where it seems to work fine.
My environment information is:
OS: Windows 10 64bit
Browser: 45.0.2454.78 beta-m (64-bit) extensions all deactivated
|
By removing the ADMIN SSL login in `wp-config.php`, I solved this.
So, remove this:
```
define('FORCE_SSL_ADMIN', true);
```
Read more about this feature [here](https://codex.wordpress.org/Administration_Over_SSL)
|
200,108 |
<p>I'm trying to give a more complete experience to my WordPress backend users and let them edit the custom image sizes I have added to my theme. </p>
<p>I added this to my <code>functions.php</code>:</p>
<pre><code>add_image_size( 'new_image_size', 500, 500, true );
</code></pre>
<p>I would like the new size to be available here:</p>
<p><a href="https://i.stack.imgur.com/GfOo7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GfOo7.png" alt="Editing an image in WordPress"></a></p>
<p>Is there a filter to add one of my custom sizes there?</p>
|
[
{
"answer_id": 207221,
"author": "user3392555",
"author_id": 82801,
"author_profile": "https://wordpress.stackexchange.com/users/82801",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think it is possible...\ni have been looking answer for this also...</p>\n\n<p>check this out...\n<a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/image-edit.php#L134\" rel=\"nofollow\">https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/image-edit.php#L134</a></p>\n\n<p>it seems hard coded... no action or filter in between...\nChanging the core is not recommended...\nand i don't think it's doing what we are expected after all...</p>\n\n<p>on Save\n<a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/image-edit.php#L767\" rel=\"nofollow\">https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/image-edit.php#L767</a></p>\n\n<p>it is only check if it is nothumb, all or original.</p>\n\n<p>and the sizes will be loaded from database options. it means all available Image Sizes including the one we add with add-image-size...</p>\n\n<p>it seems we are not be able to edit it one by one at least for now...</p>\n"
},
{
"answer_id": 226881,
"author": "jmarceli",
"author_id": 81890,
"author_profile": "https://wordpress.stackexchange.com/users/81890",
"pm_score": 3,
"selected": true,
"text": "<p>As far as i know it is possible with <code>image_size_names_choose</code> hook (see <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/image_size_names_choose\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Filter_Reference/image_size_names_choose</a>).</p>\n\n<p>Example:</p>\n\n<pre><code>// add your custom size\nfunction my_setup_image_sizes() {\n add_image_size( 'wide-image', 900, 0);\n}\nadd_action( 'after_setup_theme', 'my_setup_image_sizes' );\n\n// add custom size to editor image size options\nfunction my_editor_image_sizes( $sizes ) {\n $sizes = array_merge( $sizes, array(\n 'wide-image' => __( 'Image 900px wide' )\n ));\n return $sizes;\n}\nadd_filter( 'image_size_names_choose', 'my_editor_image_sizes' );\n</code></pre>\n\n<p><strong>NOTE</strong> You will have to regenerate thumbnails if you would like to define new image size for existing images</p>\n\n<p><strong>NOTE 2</strong> Base image size has to be greater than dimensions specified inside <code>add_image_size</code> function</p>\n"
}
] |
2015/08/29
|
[
"https://wordpress.stackexchange.com/questions/200108",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78555/"
] |
I'm trying to give a more complete experience to my WordPress backend users and let them edit the custom image sizes I have added to my theme.
I added this to my `functions.php`:
```
add_image_size( 'new_image_size', 500, 500, true );
```
I would like the new size to be available here:
[](https://i.stack.imgur.com/GfOo7.png)
Is there a filter to add one of my custom sizes there?
|
As far as i know it is possible with `image_size_names_choose` hook (see <https://codex.wordpress.org/Plugin_API/Filter_Reference/image_size_names_choose>).
Example:
```
// add your custom size
function my_setup_image_sizes() {
add_image_size( 'wide-image', 900, 0);
}
add_action( 'after_setup_theme', 'my_setup_image_sizes' );
// add custom size to editor image size options
function my_editor_image_sizes( $sizes ) {
$sizes = array_merge( $sizes, array(
'wide-image' => __( 'Image 900px wide' )
));
return $sizes;
}
add_filter( 'image_size_names_choose', 'my_editor_image_sizes' );
```
**NOTE** You will have to regenerate thumbnails if you would like to define new image size for existing images
**NOTE 2** Base image size has to be greater than dimensions specified inside `add_image_size` function
|
200,113 |
<p>We want to use wordpress to host image which we'll use in our email newsletter.</p>
<p>To that end, we can obviously upload the image via the Media panel in Admin and either right-click the image and get URL or enter <a href="http://www.wpbeginner.com/beginners-guide/how-to-get-the-url-of-images-you-upload-in-wordpress/" rel="nofollow">Library and click the image</a> to see the URL in the details area.</p>
<p>Then we could manually add the thumbnail size based on theme/settings:</p>
<pre><code>a_full_url/image.150x150.ext
</code></pre>
<p>And of course we could add the Medium or Large image into a Post or Page and right-click).</p>
<p>Is there an easier way, via the GUI that an administrator can view/get the various sizes for an image?</p>
|
[
{
"answer_id": 200140,
"author": "Ignat B.",
"author_id": 38121,
"author_profile": "https://wordpress.stackexchange.com/users/38121",
"pm_score": 2,
"selected": false,
"text": "<p>The fact that basic WP functionality wont provide you a panel to manage those sizes and retrieve media links.</p>\n\n<p>You can continue using a <code>a_full_url/image.150x150.ext</code>, or:</p>\n\n<p>1) Go-to any post/page entity via admin panel. Use 'Add image' function</p>\n\n<p>2) Select a specific size that you need and apply image</p>\n\n<p><a href=\"https://i.stack.imgur.com/z0EMY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/z0EMY.png\" alt=\"Wordpress Attachment Details\"></a></p>\n\n<p>3) Goto \"Text\" editor mode of the same post and find <code><img scr=\"YOUR_IMAGE_URL_OF_SPECIFIC_SIZE\" /></code>. Copy that and leave editor after cancelling changes.</p>\n\n<p>Complicated and not user-friendly solution, but this is what you can achieve using UI-only, without 3rd party plugins.</p>\n"
},
{
"answer_id": 200188,
"author": "Will",
"author_id": 44795,
"author_profile": "https://wordpress.stackexchange.com/users/44795",
"pm_score": 4,
"selected": true,
"text": "<p>This is a good idea. Thanks for suggesting it—going to use it. :) </p>\n\n<p>You can add a column to the Media Library that outputs the paths. This will spit them all out. You could of course filter it to only show the sizes you actually want. Put in <code>functions.php</code> or similar.</p>\n\n<pre><code>// Adds a \"Sizes\" column\nfunction sizes_column( $cols ) {\n $cols[\"sizes\"] = \"Sizes\";\n return $cols;\n}\n\n// Fill the Sizes column\nfunction sizes_value( $column_name, $id ) {\n if ( $column_name == \"sizes\" ) {\n // Including the direcory makes the list much longer \n // but required if you use /year/month for uploads\n $up_load_dir = wp_upload_dir();\n $dir = $up_load_dir['url'];\n\n // Get the info for each media item\n $meta = wp_get_attachment_metadata($id);\n\n // and loop + output\n foreach ( $meta['sizes'] as $name=>$info) {\n // could limit which sizes are output here with a simple if $name ==\n echo \"<strong>\" . $name . \"</strong><br>\";\n echo \"<small>\" . $dir . \"/\" . $info['file'] . \" </small><br>\";\n }\n }\n}\n\n// Hook actions to admin_init\nfunction hook_new_media_columns() {\n add_filter( 'manage_media_columns', 'sizes_column' );\n add_action( 'manage_media_custom_column', 'sizes_value', 10, 2 );\n}\nadd_action( 'admin_init', 'hook_new_media_columns' )\n</code></pre>\n\n<p>Using <code><small></code> as a quick and dirty hack to keep the size of long URLs in check. In production I'd probably make this a <code><dl></code> and add some admin CSS to adjust its display via site plugin.</p>\n\n<p><a href=\"https://i.stack.imgur.com/E12As.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/E12As.jpg\" alt=\"enter image description here\"></a></p>\n"
}
] |
2015/08/29
|
[
"https://wordpress.stackexchange.com/questions/200113",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48604/"
] |
We want to use wordpress to host image which we'll use in our email newsletter.
To that end, we can obviously upload the image via the Media panel in Admin and either right-click the image and get URL or enter [Library and click the image](http://www.wpbeginner.com/beginners-guide/how-to-get-the-url-of-images-you-upload-in-wordpress/) to see the URL in the details area.
Then we could manually add the thumbnail size based on theme/settings:
```
a_full_url/image.150x150.ext
```
And of course we could add the Medium or Large image into a Post or Page and right-click).
Is there an easier way, via the GUI that an administrator can view/get the various sizes for an image?
|
This is a good idea. Thanks for suggesting it—going to use it. :)
You can add a column to the Media Library that outputs the paths. This will spit them all out. You could of course filter it to only show the sizes you actually want. Put in `functions.php` or similar.
```
// Adds a "Sizes" column
function sizes_column( $cols ) {
$cols["sizes"] = "Sizes";
return $cols;
}
// Fill the Sizes column
function sizes_value( $column_name, $id ) {
if ( $column_name == "sizes" ) {
// Including the direcory makes the list much longer
// but required if you use /year/month for uploads
$up_load_dir = wp_upload_dir();
$dir = $up_load_dir['url'];
// Get the info for each media item
$meta = wp_get_attachment_metadata($id);
// and loop + output
foreach ( $meta['sizes'] as $name=>$info) {
// could limit which sizes are output here with a simple if $name ==
echo "<strong>" . $name . "</strong><br>";
echo "<small>" . $dir . "/" . $info['file'] . " </small><br>";
}
}
}
// Hook actions to admin_init
function hook_new_media_columns() {
add_filter( 'manage_media_columns', 'sizes_column' );
add_action( 'manage_media_custom_column', 'sizes_value', 10, 2 );
}
add_action( 'admin_init', 'hook_new_media_columns' )
```
Using `<small>` as a quick and dirty hack to keep the size of long URLs in check. In production I'd probably make this a `<dl>` and add some admin CSS to adjust its display via site plugin.
[](https://i.stack.imgur.com/E12As.jpg)
|
200,114 |
<p>I Just want to know how can I update my Wordpress theme manually on live site. Actually I am using plugin called "WP Total Cache" My entire website styles is messed up when I try to update wordpress theme via ftp. </p>
<p>Any suggestions please ?</p>
|
[
{
"answer_id": 200140,
"author": "Ignat B.",
"author_id": 38121,
"author_profile": "https://wordpress.stackexchange.com/users/38121",
"pm_score": 2,
"selected": false,
"text": "<p>The fact that basic WP functionality wont provide you a panel to manage those sizes and retrieve media links.</p>\n\n<p>You can continue using a <code>a_full_url/image.150x150.ext</code>, or:</p>\n\n<p>1) Go-to any post/page entity via admin panel. Use 'Add image' function</p>\n\n<p>2) Select a specific size that you need and apply image</p>\n\n<p><a href=\"https://i.stack.imgur.com/z0EMY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/z0EMY.png\" alt=\"Wordpress Attachment Details\"></a></p>\n\n<p>3) Goto \"Text\" editor mode of the same post and find <code><img scr=\"YOUR_IMAGE_URL_OF_SPECIFIC_SIZE\" /></code>. Copy that and leave editor after cancelling changes.</p>\n\n<p>Complicated and not user-friendly solution, but this is what you can achieve using UI-only, without 3rd party plugins.</p>\n"
},
{
"answer_id": 200188,
"author": "Will",
"author_id": 44795,
"author_profile": "https://wordpress.stackexchange.com/users/44795",
"pm_score": 4,
"selected": true,
"text": "<p>This is a good idea. Thanks for suggesting it—going to use it. :) </p>\n\n<p>You can add a column to the Media Library that outputs the paths. This will spit them all out. You could of course filter it to only show the sizes you actually want. Put in <code>functions.php</code> or similar.</p>\n\n<pre><code>// Adds a \"Sizes\" column\nfunction sizes_column( $cols ) {\n $cols[\"sizes\"] = \"Sizes\";\n return $cols;\n}\n\n// Fill the Sizes column\nfunction sizes_value( $column_name, $id ) {\n if ( $column_name == \"sizes\" ) {\n // Including the direcory makes the list much longer \n // but required if you use /year/month for uploads\n $up_load_dir = wp_upload_dir();\n $dir = $up_load_dir['url'];\n\n // Get the info for each media item\n $meta = wp_get_attachment_metadata($id);\n\n // and loop + output\n foreach ( $meta['sizes'] as $name=>$info) {\n // could limit which sizes are output here with a simple if $name ==\n echo \"<strong>\" . $name . \"</strong><br>\";\n echo \"<small>\" . $dir . \"/\" . $info['file'] . \" </small><br>\";\n }\n }\n}\n\n// Hook actions to admin_init\nfunction hook_new_media_columns() {\n add_filter( 'manage_media_columns', 'sizes_column' );\n add_action( 'manage_media_custom_column', 'sizes_value', 10, 2 );\n}\nadd_action( 'admin_init', 'hook_new_media_columns' )\n</code></pre>\n\n<p>Using <code><small></code> as a quick and dirty hack to keep the size of long URLs in check. In production I'd probably make this a <code><dl></code> and add some admin CSS to adjust its display via site plugin.</p>\n\n<p><a href=\"https://i.stack.imgur.com/E12As.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/E12As.jpg\" alt=\"enter image description here\"></a></p>\n"
}
] |
2015/08/30
|
[
"https://wordpress.stackexchange.com/questions/200114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78561/"
] |
I Just want to know how can I update my Wordpress theme manually on live site. Actually I am using plugin called "WP Total Cache" My entire website styles is messed up when I try to update wordpress theme via ftp.
Any suggestions please ?
|
This is a good idea. Thanks for suggesting it—going to use it. :)
You can add a column to the Media Library that outputs the paths. This will spit them all out. You could of course filter it to only show the sizes you actually want. Put in `functions.php` or similar.
```
// Adds a "Sizes" column
function sizes_column( $cols ) {
$cols["sizes"] = "Sizes";
return $cols;
}
// Fill the Sizes column
function sizes_value( $column_name, $id ) {
if ( $column_name == "sizes" ) {
// Including the direcory makes the list much longer
// but required if you use /year/month for uploads
$up_load_dir = wp_upload_dir();
$dir = $up_load_dir['url'];
// Get the info for each media item
$meta = wp_get_attachment_metadata($id);
// and loop + output
foreach ( $meta['sizes'] as $name=>$info) {
// could limit which sizes are output here with a simple if $name ==
echo "<strong>" . $name . "</strong><br>";
echo "<small>" . $dir . "/" . $info['file'] . " </small><br>";
}
}
}
// Hook actions to admin_init
function hook_new_media_columns() {
add_filter( 'manage_media_columns', 'sizes_column' );
add_action( 'manage_media_custom_column', 'sizes_value', 10, 2 );
}
add_action( 'admin_init', 'hook_new_media_columns' )
```
Using `<small>` as a quick and dirty hack to keep the size of long URLs in check. In production I'd probably make this a `<dl>` and add some admin CSS to adjust its display via site plugin.
[](https://i.stack.imgur.com/E12As.jpg)
|
200,120 |
<p>I am trying to figure out how to echo 4 created fields from a plugin in my theme template for the comment form and customize the comments output as well. The plugin I am using lets me add custom fields to comment_form but I am unable to echo out even one of them in the comments.</p>
<p>The field I am trying to echo in the code below is "$ag_condition". I also tried using the following code in a few variations and couldn't come up with anything that works.</p>
<pre><code><?php
$args = array(
'orderby' => 'comment_date',
'order' => 'DESC',
'post_type' => 'property',
);
// return a single meta value with the key 'vote' from a defined comment object
$ag_condition = get_comment_meta( $comment->comment_ID, 'agents_condition', true );
$comments = get_comments($args);
foreach($comments as $comment) :
echo('<p>' . $comment->comment_author . '</p><p>' . $comment->comment_content . '</p>');
echo ($ag_condition);
endforeach;
?>
</code></pre>
<p>I tried seeking support from the plugin forum and this is the only response I got - </p>
<blockquote>
<p>Where $meta['data_name'] is the extra field name you set in our
plugin.</p>
</blockquote>
<pre><code>echo $comment_meta_key = $meta['data_name'];
$comment_meta_val = get_comment_meta($comment -> comment_ID, $comment_meta_key, true);
</code></pre>
<p>My full code --</p>
<pre><code><?php
$args = array(
'orderby' => 'comment_date',
'order' => 'DESC',
'post_type' => 'property',
);
// return a single meta value with the key 'vote' from a defined comment object
$ag_condition = get_comment_meta( $comment->comment_ID, 'agents_condition', true );
$comments = get_comments($args);
foreach($comments as $comment) :
echo('<div id="' . $comment->comment_ID . '">Agent Name ' . $comment->comment_author . 'Phone' . $comment->comment_phone . 'Reply' . $comment->comment_content . '</div>');
echo ($ag_condition);
endforeach;
?><?php comment_form(); ?>
</code></pre>
<p>Im not sure how to correct it, any help is appreciated.</p>
<p>UPDATE</p>
<p>I tried the code and tried this other code I was trying to use to echo a custom field from the users profile (phone number) with their comment replies.</p>
<p>In the comment list I just call on the function.</p>
<p>></p>
<pre><code> function format_comment() {
> echo '<div class="comment">
> <p>'. ' $comment_author '.'</p>
> <p>'.'get_comment_meta( $comment->comment_ID, "phone", true )'.'</p> </div>' }
</code></pre>
|
[
{
"answer_id": 200140,
"author": "Ignat B.",
"author_id": 38121,
"author_profile": "https://wordpress.stackexchange.com/users/38121",
"pm_score": 2,
"selected": false,
"text": "<p>The fact that basic WP functionality wont provide you a panel to manage those sizes and retrieve media links.</p>\n\n<p>You can continue using a <code>a_full_url/image.150x150.ext</code>, or:</p>\n\n<p>1) Go-to any post/page entity via admin panel. Use 'Add image' function</p>\n\n<p>2) Select a specific size that you need and apply image</p>\n\n<p><a href=\"https://i.stack.imgur.com/z0EMY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/z0EMY.png\" alt=\"Wordpress Attachment Details\"></a></p>\n\n<p>3) Goto \"Text\" editor mode of the same post and find <code><img scr=\"YOUR_IMAGE_URL_OF_SPECIFIC_SIZE\" /></code>. Copy that and leave editor after cancelling changes.</p>\n\n<p>Complicated and not user-friendly solution, but this is what you can achieve using UI-only, without 3rd party plugins.</p>\n"
},
{
"answer_id": 200188,
"author": "Will",
"author_id": 44795,
"author_profile": "https://wordpress.stackexchange.com/users/44795",
"pm_score": 4,
"selected": true,
"text": "<p>This is a good idea. Thanks for suggesting it—going to use it. :) </p>\n\n<p>You can add a column to the Media Library that outputs the paths. This will spit them all out. You could of course filter it to only show the sizes you actually want. Put in <code>functions.php</code> or similar.</p>\n\n<pre><code>// Adds a \"Sizes\" column\nfunction sizes_column( $cols ) {\n $cols[\"sizes\"] = \"Sizes\";\n return $cols;\n}\n\n// Fill the Sizes column\nfunction sizes_value( $column_name, $id ) {\n if ( $column_name == \"sizes\" ) {\n // Including the direcory makes the list much longer \n // but required if you use /year/month for uploads\n $up_load_dir = wp_upload_dir();\n $dir = $up_load_dir['url'];\n\n // Get the info for each media item\n $meta = wp_get_attachment_metadata($id);\n\n // and loop + output\n foreach ( $meta['sizes'] as $name=>$info) {\n // could limit which sizes are output here with a simple if $name ==\n echo \"<strong>\" . $name . \"</strong><br>\";\n echo \"<small>\" . $dir . \"/\" . $info['file'] . \" </small><br>\";\n }\n }\n}\n\n// Hook actions to admin_init\nfunction hook_new_media_columns() {\n add_filter( 'manage_media_columns', 'sizes_column' );\n add_action( 'manage_media_custom_column', 'sizes_value', 10, 2 );\n}\nadd_action( 'admin_init', 'hook_new_media_columns' )\n</code></pre>\n\n<p>Using <code><small></code> as a quick and dirty hack to keep the size of long URLs in check. In production I'd probably make this a <code><dl></code> and add some admin CSS to adjust its display via site plugin.</p>\n\n<p><a href=\"https://i.stack.imgur.com/E12As.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/E12As.jpg\" alt=\"enter image description here\"></a></p>\n"
}
] |
2015/08/30
|
[
"https://wordpress.stackexchange.com/questions/200120",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24067/"
] |
I am trying to figure out how to echo 4 created fields from a plugin in my theme template for the comment form and customize the comments output as well. The plugin I am using lets me add custom fields to comment\_form but I am unable to echo out even one of them in the comments.
The field I am trying to echo in the code below is "$ag\_condition". I also tried using the following code in a few variations and couldn't come up with anything that works.
```
<?php
$args = array(
'orderby' => 'comment_date',
'order' => 'DESC',
'post_type' => 'property',
);
// return a single meta value with the key 'vote' from a defined comment object
$ag_condition = get_comment_meta( $comment->comment_ID, 'agents_condition', true );
$comments = get_comments($args);
foreach($comments as $comment) :
echo('<p>' . $comment->comment_author . '</p><p>' . $comment->comment_content . '</p>');
echo ($ag_condition);
endforeach;
?>
```
I tried seeking support from the plugin forum and this is the only response I got -
>
> Where $meta['data\_name'] is the extra field name you set in our
> plugin.
>
>
>
```
echo $comment_meta_key = $meta['data_name'];
$comment_meta_val = get_comment_meta($comment -> comment_ID, $comment_meta_key, true);
```
My full code --
```
<?php
$args = array(
'orderby' => 'comment_date',
'order' => 'DESC',
'post_type' => 'property',
);
// return a single meta value with the key 'vote' from a defined comment object
$ag_condition = get_comment_meta( $comment->comment_ID, 'agents_condition', true );
$comments = get_comments($args);
foreach($comments as $comment) :
echo('<div id="' . $comment->comment_ID . '">Agent Name ' . $comment->comment_author . 'Phone' . $comment->comment_phone . 'Reply' . $comment->comment_content . '</div>');
echo ($ag_condition);
endforeach;
?><?php comment_form(); ?>
```
Im not sure how to correct it, any help is appreciated.
UPDATE
I tried the code and tried this other code I was trying to use to echo a custom field from the users profile (phone number) with their comment replies.
In the comment list I just call on the function.
>
```
function format_comment() {
> echo '<div class="comment">
> <p>'. ' $comment_author '.'</p>
> <p>'.'get_comment_meta( $comment->comment_ID, "phone", true )'.'</p> </div>' }
```
|
This is a good idea. Thanks for suggesting it—going to use it. :)
You can add a column to the Media Library that outputs the paths. This will spit them all out. You could of course filter it to only show the sizes you actually want. Put in `functions.php` or similar.
```
// Adds a "Sizes" column
function sizes_column( $cols ) {
$cols["sizes"] = "Sizes";
return $cols;
}
// Fill the Sizes column
function sizes_value( $column_name, $id ) {
if ( $column_name == "sizes" ) {
// Including the direcory makes the list much longer
// but required if you use /year/month for uploads
$up_load_dir = wp_upload_dir();
$dir = $up_load_dir['url'];
// Get the info for each media item
$meta = wp_get_attachment_metadata($id);
// and loop + output
foreach ( $meta['sizes'] as $name=>$info) {
// could limit which sizes are output here with a simple if $name ==
echo "<strong>" . $name . "</strong><br>";
echo "<small>" . $dir . "/" . $info['file'] . " </small><br>";
}
}
}
// Hook actions to admin_init
function hook_new_media_columns() {
add_filter( 'manage_media_columns', 'sizes_column' );
add_action( 'manage_media_custom_column', 'sizes_value', 10, 2 );
}
add_action( 'admin_init', 'hook_new_media_columns' )
```
Using `<small>` as a quick and dirty hack to keep the size of long URLs in check. In production I'd probably make this a `<dl>` and add some admin CSS to adjust its display via site plugin.
[](https://i.stack.imgur.com/E12As.jpg)
|
200,129 |
<p>I'd like to create the following structure for my WP installation:</p>
<ul>
<li>htdocs (base dir)
<ul>
<li>wp (WordPress dir)</li>
<li>themes (WordPress theme dir)</li>
<li>plugins (WordPress plugin dir)</li>
<li>upload</li>
<li>index.php</li>
<li>.htaccess</li>
</ul></li>
</ul>
<p>So far I've been able to change the WordPress root directory [1] (which means that even though we're on «wp», we don't see the <a href="http://example.com/wp" rel="nofollow noreferrer">http://example.com/wp</a> url, but <a href="http://example.com" rel="nofollow noreferrer">http://example.com</a> (without /wp, which is correct for what I want). However, my first «problem» is that, when accessing to the Dashboard, I do see the '/wp/xxx' in the url. Is that normal?</p>
<p>Plugins and upload folder change work fine. [2]</p>
<p>Themes, don't work fine [3]. I've created my own extension, where I use the register_theme_directory function in the following way:</p>
<pre><code>register_theme_directory(ABSPATH . '../themes');
</code></pre>
<p>This makes the themes inside this themes folder show up in the themes selection section on the dashboard. I can select it and the theme is enabled, and it partially works (templates are correctly loaded). However, images don't load because WordPress tries to retrieve a wrong path:</p>
<pre><code>/wp/wp-content/var/www/example.com/htdocs/wp/../themes/wp-softcatala/static/images/softcatala-logotip.jpg
</code></pre>
<p>(wp-softcatala is the wordpress theme)</p>
<p>Could anyone tell me why images are not loaded correctly? Why is it using the absolute path? (all directories have correct permissions for apache)</p>
<p>Thanks</p>
<ul>
<li>[1] <a href="https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory" rel="nofollow noreferrer">https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory</a></li>
<li>[2] <a href="https://codex.wordpress.org/Editing_wp-config.php#Moving_plugin_folder" rel="nofollow noreferrer">https://codex.wordpress.org/Editing_wp-config.php#Moving_plugin_folder</a></li>
<li>[3] <a href="https://wordpress.stackexchange.com/questions/112035/how-to-move-theme-directory-but-not-plugins-uploads-out-of-wordpress-root-direct">How to move theme directory but not plugins/uploads out of WordPress root directory?</a></li>
</ul>
|
[
{
"answer_id": 200130,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>You can move the installation and also plugin and content folder. The follow source demonstrate this. </p>\n\n<pre><code>//*\n// Custom content directory\ndefine( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' );\ndefine( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' );\n// Custom plugin directory\ndefine( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' );\ndefine( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' );\n// Custom mu plugin directory\ndefine( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' );\ndefine( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' );\n/**/\n</code></pre>\n\n<p>Source for the code example. <a href=\"https://github.com/bueltge/WordPress-Starter/blob/master/wp-config.php\" rel=\"nofollow\">https://github.com/bueltge/WordPress-Starter/blob/master/wp-config.php</a></p>\n"
},
{
"answer_id": 200133,
"author": "PauGNU",
"author_id": 78569,
"author_profile": "https://wordpress.stackexchange.com/users/78569",
"pm_score": 0,
"selected": false,
"text": "<p>After some more investigation I found that the issue might be on my Timber theme. The variable that retrieves the theme path on Timber side is not correctly set. There is already an existing bug in Timber about this:</p>\n\n<p><a href=\"https://github.com/jarednova/timber/issues/619#issuecomment-136096298\" rel=\"nofollow\">https://github.com/jarednova/timber/issues/619#issuecomment-136096298</a></p>\n"
}
] |
2015/08/30
|
[
"https://wordpress.stackexchange.com/questions/200129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78569/"
] |
I'd like to create the following structure for my WP installation:
* htdocs (base dir)
+ wp (WordPress dir)
+ themes (WordPress theme dir)
+ plugins (WordPress plugin dir)
+ upload
+ index.php
+ .htaccess
So far I've been able to change the WordPress root directory [1] (which means that even though we're on «wp», we don't see the <http://example.com/wp> url, but <http://example.com> (without /wp, which is correct for what I want). However, my first «problem» is that, when accessing to the Dashboard, I do see the '/wp/xxx' in the url. Is that normal?
Plugins and upload folder change work fine. [2]
Themes, don't work fine [3]. I've created my own extension, where I use the register\_theme\_directory function in the following way:
```
register_theme_directory(ABSPATH . '../themes');
```
This makes the themes inside this themes folder show up in the themes selection section on the dashboard. I can select it and the theme is enabled, and it partially works (templates are correctly loaded). However, images don't load because WordPress tries to retrieve a wrong path:
```
/wp/wp-content/var/www/example.com/htdocs/wp/../themes/wp-softcatala/static/images/softcatala-logotip.jpg
```
(wp-softcatala is the wordpress theme)
Could anyone tell me why images are not loaded correctly? Why is it using the absolute path? (all directories have correct permissions for apache)
Thanks
* [1] <https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory>
* [2] <https://codex.wordpress.org/Editing_wp-config.php#Moving_plugin_folder>
* [3] [How to move theme directory but not plugins/uploads out of WordPress root directory?](https://wordpress.stackexchange.com/questions/112035/how-to-move-theme-directory-but-not-plugins-uploads-out-of-wordpress-root-direct)
|
You can move the installation and also plugin and content folder. The follow source demonstrate this.
```
//*
// Custom content directory
define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' );
define( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' );
// Custom plugin directory
define( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' );
define( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' );
// Custom mu plugin directory
define( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' );
define( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' );
/**/
```
Source for the code example. <https://github.com/bueltge/WordPress-Starter/blob/master/wp-config.php>
|
200,144 |
<p>I have written a custom plugin for wordpress.</p>
<p>Once I add a sub-menu to the plugin I get a double entry for the top level item:</p>
<p><a href="https://i.stack.imgur.com/WMhku.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WMhku.png" alt="enter image description here"></a></p>
<p>I would like to disable the second "TopLevel" menu item so it would appear like so:</p>
<p><a href="https://i.stack.imgur.com/g7zEN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/g7zEN.png" alt="enter image description here"></a></p>
<p>So, How do I disable the Top leve sub menu?</p>
|
[
{
"answer_id": 200145,
"author": "Rehman Ali",
"author_id": 78577,
"author_profile": "https://wordpress.stackexchange.com/users/78577",
"pm_score": -1,
"selected": false,
"text": "<p>You can easily handle via css.</p>\n\n<p>Like</p>\n\n<pre><code>.class_name{\ndisplay:none;\n}\n</code></pre>\n\n<p>Hopefully it will work for you.</p>\n"
},
{
"answer_id": 200149,
"author": "Ignat B.",
"author_id": 38121,
"author_profile": "https://wordpress.stackexchange.com/users/38121",
"pm_score": 4,
"selected": true,
"text": "<p>If you dont want 'TopLevel' menu to represent a custom page you can use:</p>\n\n<pre><code> add_menu_page( 'TopLevel', 'TopLevel', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );\n add_submenu_page( 'MENU_SLUG', 'SubMenu', 'SubMenu', 'MENU_CAP_LVL', 'SUB_MENU_SLUG', 'SUB_MENU_CB' );\n add_submenu_page( 'MENU_SLUG', 'SubMenu-A', 'SubMenu-A', 'MENU_CAP_LVL', 'SUB_MENU_A_SLUG', 'SUB_MENU_A_CB' );\n remove_submenu_page('MENU_SLUG','MENU_SLUG');\n</code></pre>\n\n<p>In this way click on \"TopMenu\" will forward to the 1st \"SubMenu\" and prevent \"TopLevel\" from being duplicate.</p>\n\n<p>Alternative solution would be a renaming the \"TopLevel\" label inside sub-menu by adding a sub menu entity with same <code>page_slug</code>, <code>menu_slug</code>, <code>function</code> (callback) as it used in <code>add_menu_page</code>:</p>\n\n<pre><code> add_menu_page( 'TopLevel', 'TopLevel', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );\n add_submenu_page( 'MENU_SLUG', 'MyRenamedTopLevelMenu', 'MyRenamedTopLevelMenu', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );\n add_submenu_page( 'MENU_SLUG', 'SubMenu', 'SubMenu', 'MENU_CAP_LVL', 'SUB_MENU_SLUG', 'SUB_MENU_CB' );\n</code></pre>\n"
}
] |
2015/08/30
|
[
"https://wordpress.stackexchange.com/questions/200144",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15010/"
] |
I have written a custom plugin for wordpress.
Once I add a sub-menu to the plugin I get a double entry for the top level item:
[](https://i.stack.imgur.com/WMhku.png)
I would like to disable the second "TopLevel" menu item so it would appear like so:
[](https://i.stack.imgur.com/g7zEN.png)
So, How do I disable the Top leve sub menu?
|
If you dont want 'TopLevel' menu to represent a custom page you can use:
```
add_menu_page( 'TopLevel', 'TopLevel', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );
add_submenu_page( 'MENU_SLUG', 'SubMenu', 'SubMenu', 'MENU_CAP_LVL', 'SUB_MENU_SLUG', 'SUB_MENU_CB' );
add_submenu_page( 'MENU_SLUG', 'SubMenu-A', 'SubMenu-A', 'MENU_CAP_LVL', 'SUB_MENU_A_SLUG', 'SUB_MENU_A_CB' );
remove_submenu_page('MENU_SLUG','MENU_SLUG');
```
In this way click on "TopMenu" will forward to the 1st "SubMenu" and prevent "TopLevel" from being duplicate.
Alternative solution would be a renaming the "TopLevel" label inside sub-menu by adding a sub menu entity with same `page_slug`, `menu_slug`, `function` (callback) as it used in `add_menu_page`:
```
add_menu_page( 'TopLevel', 'TopLevel', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );
add_submenu_page( 'MENU_SLUG', 'MyRenamedTopLevelMenu', 'MyRenamedTopLevelMenu', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );
add_submenu_page( 'MENU_SLUG', 'SubMenu', 'SubMenu', 'MENU_CAP_LVL', 'SUB_MENU_SLUG', 'SUB_MENU_CB' );
```
|
200,157 |
<p>Initially the Product Category page is divided into</p>
<p>Content Area (70% width)
Side Bar Area (30% width)
I have removed the side bar area using function.php. However the content area is still in 70%.</p>
<p>I am looking for a code with the condition in php, "If the chosen URL has Product Category with two depths, then ensure the page is full width 100%".</p>
<p><strong>What is needed: Full Width is needed for:</strong><br>
- <code>www.example.com/product-cateogry/firstdepth/</code><br>
- <code>www.example.com/product-category/firstdepth/seconddepth/</code></p>
<p><strong>full width is NOT needed for:</strong><br>
- <code>www.example.com/product-category/firstdepth/seconddepth/thirddepth</code></p>
<p>My code are below (does not work):</p>
<p>funtion.php:</p>
<pre><code>add_filter( 'body_class', 'product_categories' );
function product_categories( $classes ) {
if (is_product_category('sanitaryware') && is_product_category('Faucet')) {
$classes[] = 'product-category';
}
// return the $classes array
return $classes;
}
</code></pre>
<p>style.css:</p>
<pre><code>.ifproduct-category #content {
width: 100%;
float: none;
}
</code></pre>
<p>Theme name: Storefront</p>
|
[
{
"answer_id": 200145,
"author": "Rehman Ali",
"author_id": 78577,
"author_profile": "https://wordpress.stackexchange.com/users/78577",
"pm_score": -1,
"selected": false,
"text": "<p>You can easily handle via css.</p>\n\n<p>Like</p>\n\n<pre><code>.class_name{\ndisplay:none;\n}\n</code></pre>\n\n<p>Hopefully it will work for you.</p>\n"
},
{
"answer_id": 200149,
"author": "Ignat B.",
"author_id": 38121,
"author_profile": "https://wordpress.stackexchange.com/users/38121",
"pm_score": 4,
"selected": true,
"text": "<p>If you dont want 'TopLevel' menu to represent a custom page you can use:</p>\n\n<pre><code> add_menu_page( 'TopLevel', 'TopLevel', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );\n add_submenu_page( 'MENU_SLUG', 'SubMenu', 'SubMenu', 'MENU_CAP_LVL', 'SUB_MENU_SLUG', 'SUB_MENU_CB' );\n add_submenu_page( 'MENU_SLUG', 'SubMenu-A', 'SubMenu-A', 'MENU_CAP_LVL', 'SUB_MENU_A_SLUG', 'SUB_MENU_A_CB' );\n remove_submenu_page('MENU_SLUG','MENU_SLUG');\n</code></pre>\n\n<p>In this way click on \"TopMenu\" will forward to the 1st \"SubMenu\" and prevent \"TopLevel\" from being duplicate.</p>\n\n<p>Alternative solution would be a renaming the \"TopLevel\" label inside sub-menu by adding a sub menu entity with same <code>page_slug</code>, <code>menu_slug</code>, <code>function</code> (callback) as it used in <code>add_menu_page</code>:</p>\n\n<pre><code> add_menu_page( 'TopLevel', 'TopLevel', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );\n add_submenu_page( 'MENU_SLUG', 'MyRenamedTopLevelMenu', 'MyRenamedTopLevelMenu', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );\n add_submenu_page( 'MENU_SLUG', 'SubMenu', 'SubMenu', 'MENU_CAP_LVL', 'SUB_MENU_SLUG', 'SUB_MENU_CB' );\n</code></pre>\n"
}
] |
2015/08/30
|
[
"https://wordpress.stackexchange.com/questions/200157",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78218/"
] |
Initially the Product Category page is divided into
Content Area (70% width)
Side Bar Area (30% width)
I have removed the side bar area using function.php. However the content area is still in 70%.
I am looking for a code with the condition in php, "If the chosen URL has Product Category with two depths, then ensure the page is full width 100%".
**What is needed: Full Width is needed for:**
- `www.example.com/product-cateogry/firstdepth/`
- `www.example.com/product-category/firstdepth/seconddepth/`
**full width is NOT needed for:**
- `www.example.com/product-category/firstdepth/seconddepth/thirddepth`
My code are below (does not work):
funtion.php:
```
add_filter( 'body_class', 'product_categories' );
function product_categories( $classes ) {
if (is_product_category('sanitaryware') && is_product_category('Faucet')) {
$classes[] = 'product-category';
}
// return the $classes array
return $classes;
}
```
style.css:
```
.ifproduct-category #content {
width: 100%;
float: none;
}
```
Theme name: Storefront
|
If you dont want 'TopLevel' menu to represent a custom page you can use:
```
add_menu_page( 'TopLevel', 'TopLevel', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );
add_submenu_page( 'MENU_SLUG', 'SubMenu', 'SubMenu', 'MENU_CAP_LVL', 'SUB_MENU_SLUG', 'SUB_MENU_CB' );
add_submenu_page( 'MENU_SLUG', 'SubMenu-A', 'SubMenu-A', 'MENU_CAP_LVL', 'SUB_MENU_A_SLUG', 'SUB_MENU_A_CB' );
remove_submenu_page('MENU_SLUG','MENU_SLUG');
```
In this way click on "TopMenu" will forward to the 1st "SubMenu" and prevent "TopLevel" from being duplicate.
Alternative solution would be a renaming the "TopLevel" label inside sub-menu by adding a sub menu entity with same `page_slug`, `menu_slug`, `function` (callback) as it used in `add_menu_page`:
```
add_menu_page( 'TopLevel', 'TopLevel', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );
add_submenu_page( 'MENU_SLUG', 'MyRenamedTopLevelMenu', 'MyRenamedTopLevelMenu', 'MENU_CAP_LVL', 'MENU_SLUG', 'MENU_CB' );
add_submenu_page( 'MENU_SLUG', 'SubMenu', 'SubMenu', 'MENU_CAP_LVL', 'SUB_MENU_SLUG', 'SUB_MENU_CB' );
```
|
200,158 |
<p>I am trying to learn WP Theme development. And as I have understod it is important to use "post_class()" since plugins may need to use it. But what I not understand is where I should use it? </p>
<p>Should I use it for the post for the main loop. Or should I use it for my custom-post-type-loop. Or both?</p>
|
[
{
"answer_id": 200163,
"author": "Will",
"author_id": 44795,
"author_profile": "https://wordpress.stackexchange.com/users/44795",
"pm_score": 3,
"selected": true,
"text": "<p>It's actually only important to use it if your theme's CSS or JS is reliant on something it outputs. It essentially stuffs relevant class names into the HTML tag you put it on based on the current post/category/blah/blah. So, on a single post template this:</p>\n\n<pre><code><article <?php post_class(); ?>>\n</code></pre>\n\n<p>might output:</p>\n\n<pre><code><article class=\"post post-123 category-3 category-cats status-publish hentry\">\n</code></pre>\n\n<p>You can then use those classes to style things with CSS (or hooks for JavaScript).</p>\n\n<p>When using it with a custom post type, it will also output the post type:</p>\n\n<pre><code><article class=\"mycpt type-mycpt post-345 category-3 category-cats status-publish hentry\">\n</code></pre>\n\n<p>It actually always outputs post type. In the first example, <code>post</code> was the post type.</p>\n\n<p>Note that you can also manually pass in custom class names; since the function actually outputs the class attribute itself (vs a list of class names only) this is the only way to get both WP generated classes and custom classes onto an element. So:</p>\n\n<pre><code><article <?php post_class( 'my-custom-class' ); ?>>\n</code></pre>\n\n<p>will added <code>my-custom-class</code> to the string of classes output by WordPress.</p>\n\n<p>Codex article: <a href=\"https://codex.wordpress.org/Function_Reference/post_class\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/post_class</a></p>\n\n<p><strong>EDIT:</strong> From the comments <em>\"Okay, so post_class() should be used on the single-post-page?\"</em></p>\n\n<p>You can use it on any template. Indeed, it might even be more commonly used on archive type pages. Let's say you have a blog with three categories of posts: Tutorials, Editorials and Reviews. On your site's home page you might have a grid with all of those posts listed out in a single large list. With CSS and <code>post_class()</code> you could style each <em>type</em> of entry differently. Say, adding a graduate hat icon on anything with <code>class=\"category-tutorial\"</code>, a pencil icon on anything with <code>class=\"category-editorial\"</code> and so on.</p>\n\n<p>On <a href=\"http://ecotrust.org/search/farms\" rel=\"nofollow\">http://ecotrust.org/search/farms</a> I use the post classes on the search results page to let the user know what type of content each result is. We never got around to designing icons for each so it's simple text inserted with CSS content.</p>\n\n<pre><code>// a mixin that puts the little words in the bottom right corner\n.type-identify(@content-type:\" \") {\n &:before {\n content: @content-type;\n bottom: 20px;\n color: #cccccc;\n clear: none;\n display: block;\n position: absolute;\n right: 0;\n text-align: right;\n width: 160px;\n .small-info();\n }\n &:hover:before {\n color: #aaaaaa;\n }\n}\n\n// then call it based on the post_class() output for different post types, \n// including custom post types\n.type-post {\n .type-identify(\"Blog post\");\n}\n.type-page {\n .type-identify(\"Page\");\n}\n.type-press_release {\n .type-identify(\"Press release\");\n}\n.type-portfolio_item {\n .type-identify(\"Portfolio\");\n}\n.type-project {\n .type-identify(\"Project\");\n}\n</code></pre>\n"
},
{
"answer_id": 200169,
"author": "Ruturaj",
"author_id": 43266,
"author_profile": "https://wordpress.stackexchange.com/users/43266",
"pm_score": 0,
"selected": false,
"text": "<p>post_class will add some default Wordpress CSS Classes to the HTML tag; like <code><div <?php post_class(); ?></code></p>\n\n<p>If you want to add your own theme's custom classes, you can add those inside post_class, like so... <code><div <?php post_class('blog-entry'); ?></code>.</p>\n\n<p>You can use post_class in Loop as well as in Single/Page theme files. If used in Loop, it will allow you to give different look-n-feel for each post depending upon the Content type (standard, video, chat etc if your theme supports).</p>\n\n<p>Just to mention... see <code>body_class()</code> and use it with <code>body</code> tag; this will give you even more flexibility while writing CSS for specific pages or page-template content.</p>\n"
}
] |
2015/08/30
|
[
"https://wordpress.stackexchange.com/questions/200158",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66256/"
] |
I am trying to learn WP Theme development. And as I have understod it is important to use "post\_class()" since plugins may need to use it. But what I not understand is where I should use it?
Should I use it for the post for the main loop. Or should I use it for my custom-post-type-loop. Or both?
|
It's actually only important to use it if your theme's CSS or JS is reliant on something it outputs. It essentially stuffs relevant class names into the HTML tag you put it on based on the current post/category/blah/blah. So, on a single post template this:
```
<article <?php post_class(); ?>>
```
might output:
```
<article class="post post-123 category-3 category-cats status-publish hentry">
```
You can then use those classes to style things with CSS (or hooks for JavaScript).
When using it with a custom post type, it will also output the post type:
```
<article class="mycpt type-mycpt post-345 category-3 category-cats status-publish hentry">
```
It actually always outputs post type. In the first example, `post` was the post type.
Note that you can also manually pass in custom class names; since the function actually outputs the class attribute itself (vs a list of class names only) this is the only way to get both WP generated classes and custom classes onto an element. So:
```
<article <?php post_class( 'my-custom-class' ); ?>>
```
will added `my-custom-class` to the string of classes output by WordPress.
Codex article: <https://codex.wordpress.org/Function_Reference/post_class>
**EDIT:** From the comments *"Okay, so post\_class() should be used on the single-post-page?"*
You can use it on any template. Indeed, it might even be more commonly used on archive type pages. Let's say you have a blog with three categories of posts: Tutorials, Editorials and Reviews. On your site's home page you might have a grid with all of those posts listed out in a single large list. With CSS and `post_class()` you could style each *type* of entry differently. Say, adding a graduate hat icon on anything with `class="category-tutorial"`, a pencil icon on anything with `class="category-editorial"` and so on.
On <http://ecotrust.org/search/farms> I use the post classes on the search results page to let the user know what type of content each result is. We never got around to designing icons for each so it's simple text inserted with CSS content.
```
// a mixin that puts the little words in the bottom right corner
.type-identify(@content-type:" ") {
&:before {
content: @content-type;
bottom: 20px;
color: #cccccc;
clear: none;
display: block;
position: absolute;
right: 0;
text-align: right;
width: 160px;
.small-info();
}
&:hover:before {
color: #aaaaaa;
}
}
// then call it based on the post_class() output for different post types,
// including custom post types
.type-post {
.type-identify("Blog post");
}
.type-page {
.type-identify("Page");
}
.type-press_release {
.type-identify("Press release");
}
.type-portfolio_item {
.type-identify("Portfolio");
}
.type-project {
.type-identify("Project");
}
```
|
200,171 |
<p>I've to add just a line when the user clicks on a category link or search for something, so I thought to do something like this inside the index.php instead of creating other template file like search.php and category.php:</p>
<pre><code><?php if(is_search()): ?>
<h1><?php the_search_query(); ?></h1>
<?php endif; ?>
<?php if(is_category()): ?>
<h1><?php single_cat_title(); ?></h1>
<?php endif; ?>
</code></pre>
<p>Is it a good practice? If not, why? And which is better speaking about speed?</p>
|
[
{
"answer_id": 200173,
"author": "Ruturaj",
"author_id": 43266,
"author_profile": "https://wordpress.stackexchange.com/users/43266",
"pm_score": 0,
"selected": false,
"text": "<p>For me, it's perfect to use that sort of IF logic statements in Index than writing new template files. In fact, what you're doing in your example code is already there in themes like TweentyTwelve etc. However, if you see any chance of need for different HTML code structure in future, it's better to keep the template files separate apart. So, give it a thought; see if you just need to have a different Title for page then imho, IF statements are good to go.</p>\n"
},
{
"answer_id": 200174,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<p>Before I start, it will be a good idea to check out <a href=\"https://wordpress.stackexchange.com/a/199880/31545\">my answer</a> to the following post</p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/questions/199873/what-is-singular-php/199880#199880\">What is singular.php?</a></li>\n</ul>\n\n<p>It will give you some more insight</p>\n\n<p>As I stated in the linked answer, You can have a fully functional website with just <code>index.php</code> as template to display posts with for all pages</p>\n\n<p>What you are doing is fine, and if there are any speed difference, it should be very very minute. I would however stress that your approach might have the drawback of one templates having to do to much.</p>\n\n<p>Because you would want to do things differently for different pages, it will be a good idea to create those templates needed the relevant page loads. As I said, if there is any speed difference with any method, it would be really very very minute which you will not worry about. Having different templates for different pages with different layouts do have the advantage of that you do not overload one template with a lot of unnecessary code.</p>\n\n<p>For extra reference, see <a href=\"https://wordpress.stackexchange.com/a/200164/31545\">my answer</a> to the following post as well</p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/questions/200159/should-i-write-a-php-function-in-home-php\">Should I write a PHP function in home.php?</a></li>\n</ul>\n"
}
] |
2015/08/30
|
[
"https://wordpress.stackexchange.com/questions/200171",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78388/"
] |
I've to add just a line when the user clicks on a category link or search for something, so I thought to do something like this inside the index.php instead of creating other template file like search.php and category.php:
```
<?php if(is_search()): ?>
<h1><?php the_search_query(); ?></h1>
<?php endif; ?>
<?php if(is_category()): ?>
<h1><?php single_cat_title(); ?></h1>
<?php endif; ?>
```
Is it a good practice? If not, why? And which is better speaking about speed?
|
Before I start, it will be a good idea to check out [my answer](https://wordpress.stackexchange.com/a/199880/31545) to the following post
* [What is singular.php?](https://wordpress.stackexchange.com/questions/199873/what-is-singular-php/199880#199880)
It will give you some more insight
As I stated in the linked answer, You can have a fully functional website with just `index.php` as template to display posts with for all pages
What you are doing is fine, and if there are any speed difference, it should be very very minute. I would however stress that your approach might have the drawback of one templates having to do to much.
Because you would want to do things differently for different pages, it will be a good idea to create those templates needed the relevant page loads. As I said, if there is any speed difference with any method, it would be really very very minute which you will not worry about. Having different templates for different pages with different layouts do have the advantage of that you do not overload one template with a lot of unnecessary code.
For extra reference, see [my answer](https://wordpress.stackexchange.com/a/200164/31545) to the following post as well
* [Should I write a PHP function in home.php?](https://wordpress.stackexchange.com/questions/200159/should-i-write-a-php-function-in-home-php)
|
200,190 |
<p>I'm trying to figure out how can I display the amount of posts ever posted - not only the currently published, draft + pending etc ones, but even the deleted ones. </p>
<p>I assume that there has to be created some kind of a counter that every time a post is published gets increased by one.</p>
<p>Any ideas?</p>
<p>P.S. I'm talking about a custom post type</p>
|
[
{
"answer_id": 200192,
"author": "Will",
"author_id": 44795,
"author_profile": "https://wordpress.stackexchange.com/users/44795",
"pm_score": 0,
"selected": false,
"text": "<p>Presuming you don't empty the trash on deleted posts, you can do it with a simple <code>wp_query</code>.</p>\n\n<pre><code><?php\n$args = array (\n 'post_type' => array( 'your-custom-post-type' ),\n 'post_status' => array( 'publish', 'trash' ),\n 'posts_per_page' => -1\n);\n$query = new WP_Query( $args );\n$total = count($query->posts);\n?>\n<h1>My total: <?php echo $total; ?></h1>\n</code></pre>\n\n<p>You may need to augment the query based on the statuses you care about: <a href=\"https://codex.wordpress.org/Post_Status\" rel=\"nofollow\">https://codex.wordpress.org/Post_Status</a></p>\n"
},
{
"answer_id": 200203,
"author": "Matt Shaw",
"author_id": 77659,
"author_profile": "https://wordpress.stackexchange.com/users/77659",
"pm_score": 2,
"selected": true,
"text": "<p>Depending on your needs, WP Query may not work for this since it won't include posts that have been deleted after the trash has been emptied. This should work (but hasn't been tested):</p>\n\n<pre><code>function wpse_custom_post_type_counter() {\n $number = get_option( 'wpse_custom_counter' ) ? absint( get_option( 'wpse_custom_counter' ) ): 0;\n $number++;\n update_option( 'wpse_custom_counter', $number );\n}\nadd_action( 'publish_your_custom_post_type', 'wpse_custom_post_type_counter' );\n</code></pre>\n\n<p>You'll need to update the function and option names to suit your application. Also the slug for your custom post type should replace <code>your_custom_post_type</code> in the call to <code>add_action</code>.</p>\n\n<p>One disadvantage of this approach is that it will only work going forward, it won't be able to count existing posts.</p>\n\n<p>Hope that helps!</p>\n"
}
] |
2015/08/30
|
[
"https://wordpress.stackexchange.com/questions/200190",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69692/"
] |
I'm trying to figure out how can I display the amount of posts ever posted - not only the currently published, draft + pending etc ones, but even the deleted ones.
I assume that there has to be created some kind of a counter that every time a post is published gets increased by one.
Any ideas?
P.S. I'm talking about a custom post type
|
Depending on your needs, WP Query may not work for this since it won't include posts that have been deleted after the trash has been emptied. This should work (but hasn't been tested):
```
function wpse_custom_post_type_counter() {
$number = get_option( 'wpse_custom_counter' ) ? absint( get_option( 'wpse_custom_counter' ) ): 0;
$number++;
update_option( 'wpse_custom_counter', $number );
}
add_action( 'publish_your_custom_post_type', 'wpse_custom_post_type_counter' );
```
You'll need to update the function and option names to suit your application. Also the slug for your custom post type should replace `your_custom_post_type` in the call to `add_action`.
One disadvantage of this approach is that it will only work going forward, it won't be able to count existing posts.
Hope that helps!
|
200,212 |
<p>I have been thinking of managing a set of wordpress sites from a remote server.I would like to get information on plugins that has been installed on my wordpress sites.I would also like to install plugins to the corresponding wordpress sites from my remote server.I have searched and found that <code>XMLRPC</code> might help in retreving the details.</p>
<p>Could some one give me an idea on how this could be achieved or if there is any other means to achieve this.Thanks</p>
|
[
{
"answer_id": 200225,
"author": "Shuyinsama",
"author_id": 56771,
"author_profile": "https://wordpress.stackexchange.com/users/56771",
"pm_score": 0,
"selected": false,
"text": "<p>If you are not agains using and installing plugins on all of your servers.</p>\n\n<p>Then MainWP can be of help. While they offer a lot more then what you ask for their plugin has some solid ways of managing other installs.</p>\n\n<p>MainWP is free and open source, yet they offer some paid extra's\n<a href=\"http://www.mainwp.com\" rel=\"nofollow\">http://www.mainwp.com</a></p>\n\n<p>Alternatively you can use the XML-RPC to post to the different blogs which would require the use of a custom plugin where you create a page with a button to load plugins from either predefined sites or a checked list on the page.\nAnd then use Javascript/jQuery and AJAX to get the list of active/inactive plugins for those websites</p>\n"
},
{
"answer_id": 200244,
"author": "Zoran Petrovich",
"author_id": 78626,
"author_profile": "https://wordpress.stackexchange.com/users/78626",
"pm_score": 0,
"selected": false,
"text": "<p>Fact is, it’s pretty ridiculous that WordPress has not developed a dashboard on its own. The nice thing about it being open source, however, is that the community - which consists of extremely talented developers and designers - has a terrific ability to create plugins like ManageWP that solve problems such as this</p>\n\n<p><a href=\"http://wordpressgeekhelp.blogspot.de/2015/08/managewp-user-guide.html\" rel=\"nofollow\">http://managewp.com</a></p>\n"
},
{
"answer_id": 200298,
"author": "Will",
"author_id": 44795,
"author_profile": "https://wordpress.stackexchange.com/users/44795",
"pm_score": 2,
"selected": false,
"text": "<p>If you're only managing a few sites and you're comfortable with the command line, you might want to look into <a href=\"http://wp-cli.org/\" rel=\"nofollow\">wp-cli</a>. With a little bit of scripting you can SSH into a remote server and do all manner of stuff like:</p>\n\n<p>Enable plugins:<br>\n<code>wp plugin activate acf-pro gravityforms wordpress-seo</code></p>\n\n<p>Check the versions, activation and update availability:<br>\n<code>wp plugin status</code> </p>\n\n<p>Update all plugins, optionally doing a dry run first:<br>\n<code>wp plugin update --all --dry-run</code></p>\n\n<p>Update all themes:<br>\n<code>wp theme update</code></p>\n\n<p>And all of the other stuff wp-cli enables like:</p>\n\n<p>Back up the db:<br>\n<code>wp db backup ../data-backup-directoy</code></p>\n\n<p>Adjust posts:<br>\n<code>wp post update 6 --post_author=1</code></p>\n\n<p>Add or edit a user:<br>\n<code>wp user create sally [email protected] --role=subscriber</code></p>\n\n<p>Update options:<br>\n<code>wp option update siteurl http://foobar.com</code></p>\n\n<p>I manage most of my sites with it and a few bash scripts which consist of ssh in, do stuff, report back. Here's a script I use to backup a remote site's database, pull down a copy, load it into my local instance and reactive development-only plugins (that are disabled on the live site, natch): </p>\n\n<pre><code>#!/bin/bash\n\nDATE=`date +%Y-%m-%d-%H%M`\n\n# Backup the local db, just in case. Note that /data/local/* is .gitignored\nwp db export ../data/local/$DATE.sql\n\n# export live\nssh [email protected] \"cd /path/to/wordpress/; wp db export /path/to/site/data/live-dump-$DATE.sql\"\n\n# pull it down\nscp -Cp [email protected]:/path/to/site/data/live-dump-$DATE.sql /path/to/local/data/live-dump.sql\n\n#import it\nwp db import /path/to/local/data/live-dump.sql\n\n# reactive local developer centric plugins\nwp plugin activate debug-bar console debug-this debug-bar-extender debug-bar-hook-log\n</code></pre>\n\n<p>wp-cli is boss mode for WordPress. It even has <a href=\"https://github.com/wp-cli/wp-cli/blob/master/utils/wp-completion.bash\" rel=\"nofollow\">tab completion</a> on the command line. :)</p>\n\n<p>HumanMade was <a href=\"https://github.com/humanmade/wp-remote-cli\" rel=\"nofollow\">working on some code</a> to make remote management with it a first class citizen but it hasn't been touched in a couple of years. I find that using ssh and either running commands manually or doing a little bit of scripting is all that I really need.</p>\n"
}
] |
2015/08/31
|
[
"https://wordpress.stackexchange.com/questions/200212",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78604/"
] |
I have been thinking of managing a set of wordpress sites from a remote server.I would like to get information on plugins that has been installed on my wordpress sites.I would also like to install plugins to the corresponding wordpress sites from my remote server.I have searched and found that `XMLRPC` might help in retreving the details.
Could some one give me an idea on how this could be achieved or if there is any other means to achieve this.Thanks
|
If you're only managing a few sites and you're comfortable with the command line, you might want to look into [wp-cli](http://wp-cli.org/). With a little bit of scripting you can SSH into a remote server and do all manner of stuff like:
Enable plugins:
`wp plugin activate acf-pro gravityforms wordpress-seo`
Check the versions, activation and update availability:
`wp plugin status`
Update all plugins, optionally doing a dry run first:
`wp plugin update --all --dry-run`
Update all themes:
`wp theme update`
And all of the other stuff wp-cli enables like:
Back up the db:
`wp db backup ../data-backup-directoy`
Adjust posts:
`wp post update 6 --post_author=1`
Add or edit a user:
`wp user create sally [email protected] --role=subscriber`
Update options:
`wp option update siteurl http://foobar.com`
I manage most of my sites with it and a few bash scripts which consist of ssh in, do stuff, report back. Here's a script I use to backup a remote site's database, pull down a copy, load it into my local instance and reactive development-only plugins (that are disabled on the live site, natch):
```
#!/bin/bash
DATE=`date +%Y-%m-%d-%H%M`
# Backup the local db, just in case. Note that /data/local/* is .gitignored
wp db export ../data/local/$DATE.sql
# export live
ssh [email protected] "cd /path/to/wordpress/; wp db export /path/to/site/data/live-dump-$DATE.sql"
# pull it down
scp -Cp [email protected]:/path/to/site/data/live-dump-$DATE.sql /path/to/local/data/live-dump.sql
#import it
wp db import /path/to/local/data/live-dump.sql
# reactive local developer centric plugins
wp plugin activate debug-bar console debug-this debug-bar-extender debug-bar-hook-log
```
wp-cli is boss mode for WordPress. It even has [tab completion](https://github.com/wp-cli/wp-cli/blob/master/utils/wp-completion.bash) on the command line. :)
HumanMade was [working on some code](https://github.com/humanmade/wp-remote-cli) to make remote management with it a first class citizen but it hasn't been touched in a couple of years. I find that using ssh and either running commands manually or doing a little bit of scripting is all that I really need.
|
200,231 |
<p>As of version 4.3. it should be possible to activate markdown for my posts and comments (<a href="http://news.softpedia.com/news/say-hello-to-wordpress-4-3-489688.shtml" rel="nofollow">http://news.softpedia.com/news/say-hello-to-wordpress-4-3-489688.shtml</a>).</p>
<p>I found a description on <a href="https://en.support.wordpress.com/markdown/" rel="nofollow">https://en.support.wordpress.com/markdown/</a> , but the settings mentioned are not visible in <code>settings -> writing</code> and <code>settings -> discussion</code>.</p>
<ul>
<li>My role is <code>Administrator</code></li>
<li>The installed version is <code>Version 4.3</code></li>
</ul>
|
[
{
"answer_id": 200237,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress 4.3 have <strong>no markdown implementation</strong>, it is only a short list of shortcuts.\nThe shortcuts active on default. It give no UI area to active/deactivated them.\nAs small hint for updates posts. I seen often, that works only on new posts, no old drafts. But I haven't debug this.</p>\n\n<h3>Which Formatting Shortcuts</h3>\n\n<p>WordPress 4.3 came with a new feature called formatting shortcuts. It allows users to quickly add common text formatting without removing their hands from the keyboard and without writing any HTML.</p>\n\n<ul>\n<li>Using * or – will start an unordered list. </li>\n<li>Using 1. or 1) will start an ordered list.</li>\n<li>Using # will transform into h1. ## for h2, ### for h3 and so on.</li>\n<li>Using > will transform into blockquote.</li>\n</ul>\n\n<h3>Deactivate shortcuts</h3>\n\n<p>The only way to deactivate is a small piece of code, like in a simple custom plugin.</p>\n\n<pre><code>add_filter( 'tiny_mce_before_init', 'fb_disable_mce_wptextpattern' );\nfunction fb_disable_mce_wptextpattern( $opt ) {\n\n if ( isset( $opt['plugins'] ) && $opt['plugins'] ) {\n $opt['plugins'] = explode( ',', $opt['plugins'] );\n $opt['plugins'] = array_diff( $opt['plugins'] , array( 'wptextpattern' ) );\n $opt['plugins'] = implode( ',', $opt['plugins'] );\n }\n\n return $opt;\n}\n</code></pre>\n"
},
{
"answer_id": 325028,
"author": "Terry Lin",
"author_id": 148432,
"author_profile": "https://wordpress.stackexchange.com/users/148432",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you can try <a href=\"https://terryl.in/en/repository/wordpress-markdown-plugin-githuber-md/\" rel=\"nofollow noreferrer\">Markdown Editor plugin</a>. It supports WordPress 4.0 - 5.3</p>\n\n<p>Source code: <a href=\"https://github.com/terrylinooo/githuber-md\" rel=\"nofollow noreferrer\">https://github.com/terrylinooo/githuber-md</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/ygMM8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ygMM8.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2015/08/31
|
[
"https://wordpress.stackexchange.com/questions/200231",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63332/"
] |
As of version 4.3. it should be possible to activate markdown for my posts and comments (<http://news.softpedia.com/news/say-hello-to-wordpress-4-3-489688.shtml>).
I found a description on <https://en.support.wordpress.com/markdown/> , but the settings mentioned are not visible in `settings -> writing` and `settings -> discussion`.
* My role is `Administrator`
* The installed version is `Version 4.3`
|
WordPress 4.3 have **no markdown implementation**, it is only a short list of shortcuts.
The shortcuts active on default. It give no UI area to active/deactivated them.
As small hint for updates posts. I seen often, that works only on new posts, no old drafts. But I haven't debug this.
### Which Formatting Shortcuts
WordPress 4.3 came with a new feature called formatting shortcuts. It allows users to quickly add common text formatting without removing their hands from the keyboard and without writing any HTML.
* Using \* or – will start an unordered list.
* Using 1. or 1) will start an ordered list.
* Using # will transform into h1. ## for h2, ### for h3 and so on.
* Using > will transform into blockquote.
### Deactivate shortcuts
The only way to deactivate is a small piece of code, like in a simple custom plugin.
```
add_filter( 'tiny_mce_before_init', 'fb_disable_mce_wptextpattern' );
function fb_disable_mce_wptextpattern( $opt ) {
if ( isset( $opt['plugins'] ) && $opt['plugins'] ) {
$opt['plugins'] = explode( ',', $opt['plugins'] );
$opt['plugins'] = array_diff( $opt['plugins'] , array( 'wptextpattern' ) );
$opt['plugins'] = implode( ',', $opt['plugins'] );
}
return $opt;
}
```
|
200,243 |
<p>I am using Mochhost.com as my Hosting. Recently I have downloaded a free wp theme from wordpress.org. I unzipped the theme and I uploaded to my site at <a href="http://thegoods.info" rel="nofollow">http://thegoods.info</a> into my root directory, that is, public_html with Filezilla. Now my question is, I am unable to see the wp-content directory both in the Filezilla part as well as in my local machine. At first I thought I could not downloaded the theme properly from Wordpress.org. And for a double check I downloaded another free theme from Wordpress.org and I unzipped it and I saw the same thing, NO WP-CONTENT directory.</p>
<p>Previously I downloaded many wp themes from Wordpress.org and I purchased WP themes. But always there was this directory. I need to locate this directory in order to edit the file wp-config-sample.php file for entering my data bases there and rename this file as wp-confiq.php. To start this process I need this directory wp-content first.</p>
<p>Could you please help me to solve my issue. Would appreciate much for that.</p>
<p>Thanks
Kamrul
kochi97</p>
|
[
{
"answer_id": 200237,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress 4.3 have <strong>no markdown implementation</strong>, it is only a short list of shortcuts.\nThe shortcuts active on default. It give no UI area to active/deactivated them.\nAs small hint for updates posts. I seen often, that works only on new posts, no old drafts. But I haven't debug this.</p>\n\n<h3>Which Formatting Shortcuts</h3>\n\n<p>WordPress 4.3 came with a new feature called formatting shortcuts. It allows users to quickly add common text formatting without removing their hands from the keyboard and without writing any HTML.</p>\n\n<ul>\n<li>Using * or – will start an unordered list. </li>\n<li>Using 1. or 1) will start an ordered list.</li>\n<li>Using # will transform into h1. ## for h2, ### for h3 and so on.</li>\n<li>Using > will transform into blockquote.</li>\n</ul>\n\n<h3>Deactivate shortcuts</h3>\n\n<p>The only way to deactivate is a small piece of code, like in a simple custom plugin.</p>\n\n<pre><code>add_filter( 'tiny_mce_before_init', 'fb_disable_mce_wptextpattern' );\nfunction fb_disable_mce_wptextpattern( $opt ) {\n\n if ( isset( $opt['plugins'] ) && $opt['plugins'] ) {\n $opt['plugins'] = explode( ',', $opt['plugins'] );\n $opt['plugins'] = array_diff( $opt['plugins'] , array( 'wptextpattern' ) );\n $opt['plugins'] = implode( ',', $opt['plugins'] );\n }\n\n return $opt;\n}\n</code></pre>\n"
},
{
"answer_id": 325028,
"author": "Terry Lin",
"author_id": 148432,
"author_profile": "https://wordpress.stackexchange.com/users/148432",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you can try <a href=\"https://terryl.in/en/repository/wordpress-markdown-plugin-githuber-md/\" rel=\"nofollow noreferrer\">Markdown Editor plugin</a>. It supports WordPress 4.0 - 5.3</p>\n\n<p>Source code: <a href=\"https://github.com/terrylinooo/githuber-md\" rel=\"nofollow noreferrer\">https://github.com/terrylinooo/githuber-md</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/ygMM8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ygMM8.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2015/08/31
|
[
"https://wordpress.stackexchange.com/questions/200243",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78622/"
] |
I am using Mochhost.com as my Hosting. Recently I have downloaded a free wp theme from wordpress.org. I unzipped the theme and I uploaded to my site at <http://thegoods.info> into my root directory, that is, public\_html with Filezilla. Now my question is, I am unable to see the wp-content directory both in the Filezilla part as well as in my local machine. At first I thought I could not downloaded the theme properly from Wordpress.org. And for a double check I downloaded another free theme from Wordpress.org and I unzipped it and I saw the same thing, NO WP-CONTENT directory.
Previously I downloaded many wp themes from Wordpress.org and I purchased WP themes. But always there was this directory. I need to locate this directory in order to edit the file wp-config-sample.php file for entering my data bases there and rename this file as wp-confiq.php. To start this process I need this directory wp-content first.
Could you please help me to solve my issue. Would appreciate much for that.
Thanks
Kamrul
kochi97
|
WordPress 4.3 have **no markdown implementation**, it is only a short list of shortcuts.
The shortcuts active on default. It give no UI area to active/deactivated them.
As small hint for updates posts. I seen often, that works only on new posts, no old drafts. But I haven't debug this.
### Which Formatting Shortcuts
WordPress 4.3 came with a new feature called formatting shortcuts. It allows users to quickly add common text formatting without removing their hands from the keyboard and without writing any HTML.
* Using \* or – will start an unordered list.
* Using 1. or 1) will start an ordered list.
* Using # will transform into h1. ## for h2, ### for h3 and so on.
* Using > will transform into blockquote.
### Deactivate shortcuts
The only way to deactivate is a small piece of code, like in a simple custom plugin.
```
add_filter( 'tiny_mce_before_init', 'fb_disable_mce_wptextpattern' );
function fb_disable_mce_wptextpattern( $opt ) {
if ( isset( $opt['plugins'] ) && $opt['plugins'] ) {
$opt['plugins'] = explode( ',', $opt['plugins'] );
$opt['plugins'] = array_diff( $opt['plugins'] , array( 'wptextpattern' ) );
$opt['plugins'] = implode( ',', $opt['plugins'] );
}
return $opt;
}
```
|
200,245 |
<p>I have div structure</p>
<pre><code><div class = 'main-menu'>
<ul class = 'menu'>
<li class = 'item1'></li>
<li class = 'item2'></li>
</ul>
</div>
</code></pre>
<p>But I want add div to menu </p>
<pre><code><div class = 'main-menu'>
<ul class = 'menu'>
<li class = 'item1'></li>
<li class = 'item2'>
<div class="adv_categories" id="adv_categories">
<?php cp_create_categories_list( 'menu' ) ?>
</div>
</li>
</ul>
</div>
</code></pre>
<p>How can I do that?</p>
|
[
{
"answer_id": 200237,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress 4.3 have <strong>no markdown implementation</strong>, it is only a short list of shortcuts.\nThe shortcuts active on default. It give no UI area to active/deactivated them.\nAs small hint for updates posts. I seen often, that works only on new posts, no old drafts. But I haven't debug this.</p>\n\n<h3>Which Formatting Shortcuts</h3>\n\n<p>WordPress 4.3 came with a new feature called formatting shortcuts. It allows users to quickly add common text formatting without removing their hands from the keyboard and without writing any HTML.</p>\n\n<ul>\n<li>Using * or – will start an unordered list. </li>\n<li>Using 1. or 1) will start an ordered list.</li>\n<li>Using # will transform into h1. ## for h2, ### for h3 and so on.</li>\n<li>Using > will transform into blockquote.</li>\n</ul>\n\n<h3>Deactivate shortcuts</h3>\n\n<p>The only way to deactivate is a small piece of code, like in a simple custom plugin.</p>\n\n<pre><code>add_filter( 'tiny_mce_before_init', 'fb_disable_mce_wptextpattern' );\nfunction fb_disable_mce_wptextpattern( $opt ) {\n\n if ( isset( $opt['plugins'] ) && $opt['plugins'] ) {\n $opt['plugins'] = explode( ',', $opt['plugins'] );\n $opt['plugins'] = array_diff( $opt['plugins'] , array( 'wptextpattern' ) );\n $opt['plugins'] = implode( ',', $opt['plugins'] );\n }\n\n return $opt;\n}\n</code></pre>\n"
},
{
"answer_id": 325028,
"author": "Terry Lin",
"author_id": 148432,
"author_profile": "https://wordpress.stackexchange.com/users/148432",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you can try <a href=\"https://terryl.in/en/repository/wordpress-markdown-plugin-githuber-md/\" rel=\"nofollow noreferrer\">Markdown Editor plugin</a>. It supports WordPress 4.0 - 5.3</p>\n\n<p>Source code: <a href=\"https://github.com/terrylinooo/githuber-md\" rel=\"nofollow noreferrer\">https://github.com/terrylinooo/githuber-md</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/ygMM8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ygMM8.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2015/08/31
|
[
"https://wordpress.stackexchange.com/questions/200245",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78447/"
] |
I have div structure
```
<div class = 'main-menu'>
<ul class = 'menu'>
<li class = 'item1'></li>
<li class = 'item2'></li>
</ul>
</div>
```
But I want add div to menu
```
<div class = 'main-menu'>
<ul class = 'menu'>
<li class = 'item1'></li>
<li class = 'item2'>
<div class="adv_categories" id="adv_categories">
<?php cp_create_categories_list( 'menu' ) ?>
</div>
</li>
</ul>
</div>
```
How can I do that?
|
WordPress 4.3 have **no markdown implementation**, it is only a short list of shortcuts.
The shortcuts active on default. It give no UI area to active/deactivated them.
As small hint for updates posts. I seen often, that works only on new posts, no old drafts. But I haven't debug this.
### Which Formatting Shortcuts
WordPress 4.3 came with a new feature called formatting shortcuts. It allows users to quickly add common text formatting without removing their hands from the keyboard and without writing any HTML.
* Using \* or – will start an unordered list.
* Using 1. or 1) will start an ordered list.
* Using # will transform into h1. ## for h2, ### for h3 and so on.
* Using > will transform into blockquote.
### Deactivate shortcuts
The only way to deactivate is a small piece of code, like in a simple custom plugin.
```
add_filter( 'tiny_mce_before_init', 'fb_disable_mce_wptextpattern' );
function fb_disable_mce_wptextpattern( $opt ) {
if ( isset( $opt['plugins'] ) && $opt['plugins'] ) {
$opt['plugins'] = explode( ',', $opt['plugins'] );
$opt['plugins'] = array_diff( $opt['plugins'] , array( 'wptextpattern' ) );
$opt['plugins'] = implode( ',', $opt['plugins'] );
}
return $opt;
}
```
|
200,276 |
<p>I want to know who added every user in all users menu in the back-end, I used 'get_the_author' but it must be within the 'loop' which cann't be in all users menu that the condnition willnot be verified, Could anyone help?</p>
|
[
{
"answer_id": 200237,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress 4.3 have <strong>no markdown implementation</strong>, it is only a short list of shortcuts.\nThe shortcuts active on default. It give no UI area to active/deactivated them.\nAs small hint for updates posts. I seen often, that works only on new posts, no old drafts. But I haven't debug this.</p>\n\n<h3>Which Formatting Shortcuts</h3>\n\n<p>WordPress 4.3 came with a new feature called formatting shortcuts. It allows users to quickly add common text formatting without removing their hands from the keyboard and without writing any HTML.</p>\n\n<ul>\n<li>Using * or – will start an unordered list. </li>\n<li>Using 1. or 1) will start an ordered list.</li>\n<li>Using # will transform into h1. ## for h2, ### for h3 and so on.</li>\n<li>Using > will transform into blockquote.</li>\n</ul>\n\n<h3>Deactivate shortcuts</h3>\n\n<p>The only way to deactivate is a small piece of code, like in a simple custom plugin.</p>\n\n<pre><code>add_filter( 'tiny_mce_before_init', 'fb_disable_mce_wptextpattern' );\nfunction fb_disable_mce_wptextpattern( $opt ) {\n\n if ( isset( $opt['plugins'] ) && $opt['plugins'] ) {\n $opt['plugins'] = explode( ',', $opt['plugins'] );\n $opt['plugins'] = array_diff( $opt['plugins'] , array( 'wptextpattern' ) );\n $opt['plugins'] = implode( ',', $opt['plugins'] );\n }\n\n return $opt;\n}\n</code></pre>\n"
},
{
"answer_id": 325028,
"author": "Terry Lin",
"author_id": 148432,
"author_profile": "https://wordpress.stackexchange.com/users/148432",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you can try <a href=\"https://terryl.in/en/repository/wordpress-markdown-plugin-githuber-md/\" rel=\"nofollow noreferrer\">Markdown Editor plugin</a>. It supports WordPress 4.0 - 5.3</p>\n\n<p>Source code: <a href=\"https://github.com/terrylinooo/githuber-md\" rel=\"nofollow noreferrer\">https://github.com/terrylinooo/githuber-md</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/ygMM8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ygMM8.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2015/08/31
|
[
"https://wordpress.stackexchange.com/questions/200276",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78311/"
] |
I want to know who added every user in all users menu in the back-end, I used 'get\_the\_author' but it must be within the 'loop' which cann't be in all users menu that the condnition willnot be verified, Could anyone help?
|
WordPress 4.3 have **no markdown implementation**, it is only a short list of shortcuts.
The shortcuts active on default. It give no UI area to active/deactivated them.
As small hint for updates posts. I seen often, that works only on new posts, no old drafts. But I haven't debug this.
### Which Formatting Shortcuts
WordPress 4.3 came with a new feature called formatting shortcuts. It allows users to quickly add common text formatting without removing their hands from the keyboard and without writing any HTML.
* Using \* or – will start an unordered list.
* Using 1. or 1) will start an ordered list.
* Using # will transform into h1. ## for h2, ### for h3 and so on.
* Using > will transform into blockquote.
### Deactivate shortcuts
The only way to deactivate is a small piece of code, like in a simple custom plugin.
```
add_filter( 'tiny_mce_before_init', 'fb_disable_mce_wptextpattern' );
function fb_disable_mce_wptextpattern( $opt ) {
if ( isset( $opt['plugins'] ) && $opt['plugins'] ) {
$opt['plugins'] = explode( ',', $opt['plugins'] );
$opt['plugins'] = array_diff( $opt['plugins'] , array( 'wptextpattern' ) );
$opt['plugins'] = implode( ',', $opt['plugins'] );
}
return $opt;
}
```
|
200,294 |
<p>I have a bit of content in a PHP file that is designed to live inside an iframe on another page. The PHP file is very simple-- here it is in its entirety right now:</p>
<pre><code><div class="content-tos">
<?php
// get the terms of service from other page
$getpage = get_page_by_path('/terms-of-service');
echo apply_filters('the_content', $getpage->post_content);
?>
</div>
</code></pre>
<p>Obviously I need to include something above these lines of code so the PHP has access to the Wordpress core functions (like <code>get_page_by_path()</code>)... but if I use <code>get_header()</code> I get my entire header, nav bar, Google Analytics tracking code etc, which then appear inside the iframe, which I definitely don't want.</p>
<p>Is there a way in Wordpress to do some kind of include that will give me the basic Wordpress API but won't draw a full HTML header, etc, etc, etc from the <code>header.php</code> file?</p>
|
[
{
"answer_id": 200299,
"author": "Will",
"author_id": 44795,
"author_profile": "https://wordpress.stackexchange.com/users/44795",
"pm_score": 0,
"selected": false,
"text": "<p>Think perhaps you're confusing <code>get_header()</code> with the file <code>wp-blog-header.php</code>. The first is a theming function generally used to pull stuff into the <code><head></code> section of your HTML. The file <code>wp-blog-header.php</code> essentially bootstraps WordPress. </p>\n\n<p>Try this:</p>\n\n<pre><code><div class=\"content-tos\">\n <?php\n require('/path/wordpress/wp-blog-header.php');\n // get the terms of service from other page\n $getpage = get_page_by_path('/terms-of-service');\n echo apply_filters('the_content', $getpage->post_content);\n ?>\n</div>\n</code></pre>\n"
},
{
"answer_id": 200301,
"author": "totels",
"author_id": 23446,
"author_profile": "https://wordpress.stackexchange.com/users/23446",
"pm_score": 3,
"selected": true,
"text": "<p>If you don't want <code>get_header</code>, then don't call <code>get_header()</code>. It's a simple as that, the <code>get_header</code> function is not where all of the WP core is initialized. The simplest way to do this is using the template hierarchy to create a template for a specific page slug or id.</p>\n\n<p>From the WP Admin, create a page at the URL you want to use.</p>\n\n<pre><code>http://example.com/tos\n</code></pre>\n\n<p>Then create a template file that <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">follows the rules for overriding the template</a> for that specific page.</p>\n\n<pre><code>wp-content/themes/<your-theme>/page-tos.php\n</code></pre>\n\n<p>From there you can put whatever you want in <code>page-tos.php</code> and have full access to WP functions and API. And you can disable it by simply unpublishing the page from the WP Admin as well.</p>\n"
}
] |
2015/08/31
|
[
"https://wordpress.stackexchange.com/questions/200294",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13981/"
] |
I have a bit of content in a PHP file that is designed to live inside an iframe on another page. The PHP file is very simple-- here it is in its entirety right now:
```
<div class="content-tos">
<?php
// get the terms of service from other page
$getpage = get_page_by_path('/terms-of-service');
echo apply_filters('the_content', $getpage->post_content);
?>
</div>
```
Obviously I need to include something above these lines of code so the PHP has access to the Wordpress core functions (like `get_page_by_path()`)... but if I use `get_header()` I get my entire header, nav bar, Google Analytics tracking code etc, which then appear inside the iframe, which I definitely don't want.
Is there a way in Wordpress to do some kind of include that will give me the basic Wordpress API but won't draw a full HTML header, etc, etc, etc from the `header.php` file?
|
If you don't want `get_header`, then don't call `get_header()`. It's a simple as that, the `get_header` function is not where all of the WP core is initialized. The simplest way to do this is using the template hierarchy to create a template for a specific page slug or id.
From the WP Admin, create a page at the URL you want to use.
```
http://example.com/tos
```
Then create a template file that [follows the rules for overriding the template](https://developer.wordpress.org/themes/basics/template-hierarchy/) for that specific page.
```
wp-content/themes/<your-theme>/page-tos.php
```
From there you can put whatever you want in `page-tos.php` and have full access to WP functions and API. And you can disable it by simply unpublishing the page from the WP Admin as well.
|
200,296 |
<p>WordPress 4.3 brought more updates to the customizer. It also added a new option at the top admin menu bar that says 'Cusomize' and has a paintbrush. How can I disable this menu from showing up? We don't use the customizer, and I would not like our users clicking on it either. </p>
<p>We currently do <code>$wp_admin_bar->remove_menu('comments');</code> but I do not know the term for the customizer. I tried both customize and customizer (guessing) but neither seemed to work. </p>
|
[
{
"answer_id": 200304,
"author": "czerspalace",
"author_id": 47406,
"author_profile": "https://wordpress.stackexchange.com/users/47406",
"pm_score": 5,
"selected": true,
"text": "<p><code>customize</code> should work. I was able to remove the Customize link with the following code:</p>\n\n<pre><code>add_action( 'wp_before_admin_bar_render', 'wpse200296_before_admin_bar_render' ); \n\nfunction wpse200296_before_admin_bar_render()\n{\n global $wp_admin_bar;\n\n $wp_admin_bar->remove_menu('customize');\n}\n</code></pre>\n"
},
{
"answer_id": 201646,
"author": "LoicTheAztec",
"author_id": 79855,
"author_profile": "https://wordpress.stackexchange.com/users/79855",
"pm_score": 3,
"selected": false,
"text": "<p>Or this more compact one will do the same :</p>\n\n<pre><code>add_action( 'admin_bar_menu', 'remove_some_nodes_from_admin_top_bar_menu', 999 );\nfunction remove_some_nodes_from_admin_top_bar_menu( $wp_admin_bar ) {\n $wp_admin_bar->remove_menu( 'customize' );\n}\n</code></pre>\n\n<p>Regards</p>\n"
},
{
"answer_id": 409986,
"author": "thetwopct",
"author_id": 135299,
"author_profile": "https://wordpress.stackexchange.com/users/135299",
"pm_score": 0,
"selected": false,
"text": "<p>Neither of the solutions posted here worked for me. Instead I used the following:</p>\n<pre><code>/**\n * Remove elements from sidebar.\n */\nfunction remove_customize_from_admin_sidebar() {\n\n remove_submenu_page( 'themes.php', 'customize.php?return=%2Fwp-admin%2Fthemes.php' );\n\n}\nadd_action( 'admin_menu', 'remove_customize_from_admin_sidebar' );\n</code></pre>\n<p>This uses the <a href=\"https://developer.wordpress.org/reference/functions/remove_submenu_page/\" rel=\"nofollow noreferrer\">remove_submenu_page()</a> function to specify the parent link (themes.php) and then the child link - in this case the Customize URL.</p>\n<p>If you want to remove parent menu items, you can use <a href=\"https://developer.wordpress.org/reference/functions/remove_menu_page/\" rel=\"nofollow noreferrer\">remove_menu_page()</a>, for example:</p>\n<pre><code>remove_menu_page( 'edit-comments.php' );\n</code></pre>\n"
}
] |
2015/08/31
|
[
"https://wordpress.stackexchange.com/questions/200296",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17423/"
] |
WordPress 4.3 brought more updates to the customizer. It also added a new option at the top admin menu bar that says 'Cusomize' and has a paintbrush. How can I disable this menu from showing up? We don't use the customizer, and I would not like our users clicking on it either.
We currently do `$wp_admin_bar->remove_menu('comments');` but I do not know the term for the customizer. I tried both customize and customizer (guessing) but neither seemed to work.
|
`customize` should work. I was able to remove the Customize link with the following code:
```
add_action( 'wp_before_admin_bar_render', 'wpse200296_before_admin_bar_render' );
function wpse200296_before_admin_bar_render()
{
global $wp_admin_bar;
$wp_admin_bar->remove_menu('customize');
}
```
|
200,315 |
<p>I am trying to learn WP theme development. And at the moment I got some problems when I try to enqueue my stylesheet (id does'nt load). It is named style.css and located in my theme folder.</p>
<p>I have put this code in my functions.php file:</p>
<pre><code>function my_theme_scripts() {
wp_register_style( 'style', get_stylesheet_uri() );
wp_enqueue_style( 'style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
</code></pre>
<p>I can't understand what I am doing wrong? I have been reading the codex upside down. What am I doing wrong?</p>
|
[
{
"answer_id": 200316,
"author": "andreiudeiu",
"author_id": 74500,
"author_profile": "https://wordpress.stackexchange.com/users/74500",
"pm_score": 1,
"selected": false,
"text": "<p>try define the css url.</p>\n\n<p>for example this:</p>\n\n<p>wp_register_style('style', get_template_directory_uri() . '/css/custom_css.css') );</p>\n"
},
{
"answer_id": 200320,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 2,
"selected": false,
"text": "<p>Please edit the path for the style sheet</p>\n\n<p>And put the code in functions.php</p>\n\n<pre><code>function my_theme_scripts() {\nwp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css',false,'all' );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_scripts' );\n</code></pre>\n"
}
] |
2015/08/31
|
[
"https://wordpress.stackexchange.com/questions/200315",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66256/"
] |
I am trying to learn WP theme development. And at the moment I got some problems when I try to enqueue my stylesheet (id does'nt load). It is named style.css and located in my theme folder.
I have put this code in my functions.php file:
```
function my_theme_scripts() {
wp_register_style( 'style', get_stylesheet_uri() );
wp_enqueue_style( 'style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
```
I can't understand what I am doing wrong? I have been reading the codex upside down. What am I doing wrong?
|
Please edit the path for the style sheet
And put the code in functions.php
```
function my_theme_scripts() {
wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css',false,'all' );
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
```
|
200,338 |
<p>How can I add a button to a posts -page. (In this case a custom post type).</p>
<p>I'd like to place it next to, or near, the "Add new" button, to import content from a web service.</p>
|
[
{
"answer_id": 200340,
"author": "Marek",
"author_id": 54031,
"author_profile": "https://wordpress.stackexchange.com/users/54031",
"pm_score": 3,
"selected": false,
"text": "<p>Like this:</p>\n\n<pre><code>function custom_js_to_head() {\n ?>\n <script>\n jQuery(function(){\n jQuery(\"body.post-type-YOUR-CUSTOM-POST-TYPE .wrap h1\").append('<a href=\"index.php?param=your-action\" class=\"page-title-action\">Import from ...</a>');\n });\n </script>\n <?php\n}\nadd_action('admin_head', 'custom_js_to_head');\n</code></pre>\n\n<p>That code (pasted to functions.php) will dynamically add new link tag after \"Add new\" link. </p>\n"
},
{
"answer_id": 200349,
"author": "ahmetlutfu",
"author_id": 25086,
"author_profile": "https://wordpress.stackexchange.com/users/25086",
"pm_score": 3,
"selected": false,
"text": "<p>You can add button via <a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\" rel=\"noreferrer\">add_meta_box</a> function. </p>\n\n<pre><code>function add_your_meta_box(){\n\nadd_meta_box('your-metabox-id', 'Title', 'function_of_metabox', 'custom_post_type', 'side', 'high');}\n\nadd_action('add_meta_boxes', 'add_your_meta_box'); \n\nfunction function_of_metabox()\n{?>\n <input type=\"submit\" class=\"button button-primary button-large\" value=\"Add New\" id=\"add-new\"/>\n<?php }\n</code></pre>\n\n<p>if you add to multiple post type, you should use foreach loop.</p>\n\n<pre><code>function add_your_meta_box(){\n\n $types = array(\"post\",\"page\",\"custom_post_type\");\n\n foreach($types as $type){\n\n add_meta_box('your-metabox-id', 'Title', 'function_of_metabox', $type, 'side', 'high');}\n\n}\n\nadd_action('add_meta_boxes', 'add_your_meta_box'); \n</code></pre>\n"
}
] |
2015/09/01
|
[
"https://wordpress.stackexchange.com/questions/200338",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78679/"
] |
How can I add a button to a posts -page. (In this case a custom post type).
I'd like to place it next to, or near, the "Add new" button, to import content from a web service.
|
Like this:
```
function custom_js_to_head() {
?>
<script>
jQuery(function(){
jQuery("body.post-type-YOUR-CUSTOM-POST-TYPE .wrap h1").append('<a href="index.php?param=your-action" class="page-title-action">Import from ...</a>');
});
</script>
<?php
}
add_action('admin_head', 'custom_js_to_head');
```
That code (pasted to functions.php) will dynamically add new link tag after "Add new" link.
|
200,368 |
<p>I'm trying to setup a cron to run every hour, it works fine on my local vagrant box, but it doesn't seem to schedule properly on aws(elastic beanstalk). Here's the code:</p>
<pre><code>register_activation_hook(__FILE__, 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');
function my_activation() {
wp_schedule_event(time(), 'hourly', 'my_hourly_event');
}
function do_this_hourly() {
another_function();
}
register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
wp_clear_scheduled_hook('my_hourly_event');
}
</code></pre>
<p>is something wrong with this, or is something else at play?</p>
<p>I have w3 total cache installed both locally and on aws, so I don't think that would be to blame, as I've heard people mention it.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 215395,
"author": "Peyman Mohamadpour",
"author_id": 75020,
"author_profile": "https://wordpress.stackexchange.com/users/75020",
"pm_score": 0,
"selected": false,
"text": "<p>You may use these steps to get it to work:`\n<strong>1. Setup an schedule</strong></p>\n\n<pre><code>function my_schedule( $schedules ) {\n $schedules['hourly'] = array(\n 'interval' => 60 * 60,\n 'display' => __( 'One houre' )\n );\n return $schedules;\n}\nadd_filter( 'cron_schedules', 'my_schedule' );\n</code></pre>\n\n<p><strong>2. Register the activation hook</strong></p>\n\n<pre><code>register_activation_hook( __FILE__, 'my_activation' );\n\nfunction my_activation() {\n $timestamp = wp_next_scheduled( 'my_hourly_event' );\n if( false == $timestamp ){\n wp_schedule_event( time(), 'hourly', 'my_hourly_event' );\n }\n}\n</code></pre>\n\n<p><strong>3. Add action on the event</strong></p>\n\n<pre><code>function do_this_hourly() {\n // The cron functionality and rest of your code here\n}\nadd_action( 'my_hourly_event', 'do_this_hourly' );\n</code></pre>\n"
},
{
"answer_id": 276109,
"author": "Jim Maguire",
"author_id": 63669,
"author_profile": "https://wordpress.stackexchange.com/users/63669",
"pm_score": 1,
"selected": false,
"text": "<p>As a general principal, you shouldn't do anything that requires an 'add_action' after the plugin activation hook. This is because WP loads and runs all plugins and THEN runs the new added one, and then does a re-direct. You have to set a DB option and hook into that. Here is the discussion from the CODEX:\n<a href=\"https://codex.wordpress.org/Function_Reference/register_activation_hook\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_activation_hook</a></p>\n\n<p>Try doing this outside of the activation hook and see what happens.In other words, PHP runs through the whole Wordpress routine on each browser request. When you 'activate' a plugin, you actually fire two page requests to the server. This type of activity properly goes in the 2nd page request, which is the re-direct. </p>\n"
}
] |
2015/09/01
|
[
"https://wordpress.stackexchange.com/questions/200368",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/72925/"
] |
I'm trying to setup a cron to run every hour, it works fine on my local vagrant box, but it doesn't seem to schedule properly on aws(elastic beanstalk). Here's the code:
```
register_activation_hook(__FILE__, 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');
function my_activation() {
wp_schedule_event(time(), 'hourly', 'my_hourly_event');
}
function do_this_hourly() {
another_function();
}
register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
wp_clear_scheduled_hook('my_hourly_event');
}
```
is something wrong with this, or is something else at play?
I have w3 total cache installed both locally and on aws, so I don't think that would be to blame, as I've heard people mention it.
Thanks.
|
As a general principal, you shouldn't do anything that requires an 'add\_action' after the plugin activation hook. This is because WP loads and runs all plugins and THEN runs the new added one, and then does a re-direct. You have to set a DB option and hook into that. Here is the discussion from the CODEX:
<https://codex.wordpress.org/Function_Reference/register_activation_hook>
Try doing this outside of the activation hook and see what happens.In other words, PHP runs through the whole Wordpress routine on each browser request. When you 'activate' a plugin, you actually fire two page requests to the server. This type of activity properly goes in the 2nd page request, which is the re-direct.
|
200,373 |
<p>I have a parent class, which contains the following:</p>
<pre><code>use app\My_Dashboard;
class My_Class {
public function __construct() {
add_action('admin_menu', array($this, 'setup_dashboard_page'));
}
public function setup_dashboard_page() {
My_Dashboard::add_dashboard_page();
}
}
</code></pre>
<p>And the class which has the admin page functions:</p>
<pre><code>class My_Dashboard {
public static function add_dashboard_page() {
add_menu_page('My Settings', 'My Settings', 'my-settings', array($this, 'dashboard_page_cb'));
}
public function dashboard_page_cb() {
//The markup
}
}
</code></pre>
<p>This approach doesn't work, and I cannot see my admin menu item and page added. The second approach I tried:</p>
<pre><code>use app\My_Dashboard;
class My_Class {
public function __construct() {
add_action('admin_menu', array($this, 'setup_dashboard_page'));
}
public function setup_dashboard_page() {
//Not very sure of the syntax, bad at OOP
add_menu_page('My Settings', 'My Settings', 'my-settings', 'My_Dashboard::dashboard_page_cb');
}
}
</code></pre>
<p>How do I get it to work? My idea is to separate all the dashboard related stuff to the other class.</p>
<p><strong>Update:</strong>
The first approach worked, and the menu item is added. But the callback function that outputs the page markup doesn't seem to work. I checked for typos but everything seems okay.</p>
|
[
{
"answer_id": 200379,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": true,
"text": "<p>I hate OOP mixed in the functional structure of wordpress (here come the downvotes.....). If you use OOP just for name spacing then just use the name spacing feature of PHP, putting function in a class is just a very small part of what OOP should be.</p>\n\n<p>Anyway, your problems is that a there are only two way to refere to an class method, either when it is associated with a <strong>specific</strong> object or if it is static in the class (basically associated with the class but not with the objects). In your code you try to treat an object bound function as if it is a static one (I am sure that if you will check your error log you will see some relevant error). There are two possible way to fix it \n1. Make the relevant functions static and use the syntax in your second variation\n2. use a singleton patter, instantiate an object of the dashboard class, keep it as a global and use it instead of the class name in your first variation. instead of </p>\n\n<pre><code>public function setup_dashboard_page() {\n My_Dashboard::add_dashboard_page();\n}\n</code></pre>\n\n<p>do </p>\n\n<pre><code>global $dashboard;\n$dashboard = new my_dashboard()\n.....\npublic function setup_dashboard_page() {\n global $dashboard;\n $dashboard->add_dashboard_page();\n}\n</code></pre>\n\n<p>And always debug code with full error reporting and fix all errors and notices ;)</p>\n"
},
{
"answer_id": 257816,
"author": "Amjad Ali",
"author_id": 114120,
"author_profile": "https://wordpress.stackexchange.com/users/114120",
"pm_score": 2,
"selected": false,
"text": "<p>Working Example</p>\n\n<pre><code>class PluginSkeleton {\n\n public function __construct(){\n add_action('admin_menu',array($this,'pluginskeleton_menu'));\n }\n public function pluginskeleton_menu(){\n add_menu_page( 'Application Users', 'Application Users', 'manage_options', 'application-users.php',array($this,'application_users_page'));\n }\n\n public function application_users_page(){\n echo 'i am here';\n }\n\n}\n</code></pre>\n\n<p>use $this with callback function</p>\n\n<pre><code>add_menu_page( 'Application Users', '...', ...', '...',array($this,'application_users_page'));\n</code></pre>\n"
},
{
"answer_id": 370179,
"author": "Amigo Dheena",
"author_id": 190929,
"author_profile": "https://wordpress.stackexchange.com/users/190929",
"pm_score": 0,
"selected": false,
"text": "<p>You can simply add your menu page like this, I hope it's a simple approach</p>\n<pre class=\"lang-php prettyprint-override\"><code>class MyPlugin{\n\n function __construct()\n {\n add_action('admin_menu', array($this, 'add_menu_page_fun'));\n }\n\n // Add Menu Page\n function add_menu_page_fun() { \n add_menu_page(\n __('My Plugin Page','myplugin-menupage'), //Page title\n __('My Plugin Title','myplugin-menu'), //Menu title\n 'manage_options', //capability\n 'my-plug-handle', //menu_slug\n array($this, 'toplevel_page'), //function\n 'dashicons-buddicons-activity' //icon url\n );\n }\n \n // Displays the page content for the custom Toplevel menu\n function toplevel_page() {\n // echo "<h2>" . __( 'Welcome to admin page', 'myplugin-menu' ) . "</h2>";\n include 'My-admin.php'; //new php file\n }\n\n}\n</code></pre>\n"
}
] |
2015/09/01
|
[
"https://wordpress.stackexchange.com/questions/200373",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4740/"
] |
I have a parent class, which contains the following:
```
use app\My_Dashboard;
class My_Class {
public function __construct() {
add_action('admin_menu', array($this, 'setup_dashboard_page'));
}
public function setup_dashboard_page() {
My_Dashboard::add_dashboard_page();
}
}
```
And the class which has the admin page functions:
```
class My_Dashboard {
public static function add_dashboard_page() {
add_menu_page('My Settings', 'My Settings', 'my-settings', array($this, 'dashboard_page_cb'));
}
public function dashboard_page_cb() {
//The markup
}
}
```
This approach doesn't work, and I cannot see my admin menu item and page added. The second approach I tried:
```
use app\My_Dashboard;
class My_Class {
public function __construct() {
add_action('admin_menu', array($this, 'setup_dashboard_page'));
}
public function setup_dashboard_page() {
//Not very sure of the syntax, bad at OOP
add_menu_page('My Settings', 'My Settings', 'my-settings', 'My_Dashboard::dashboard_page_cb');
}
}
```
How do I get it to work? My idea is to separate all the dashboard related stuff to the other class.
**Update:**
The first approach worked, and the menu item is added. But the callback function that outputs the page markup doesn't seem to work. I checked for typos but everything seems okay.
|
I hate OOP mixed in the functional structure of wordpress (here come the downvotes.....). If you use OOP just for name spacing then just use the name spacing feature of PHP, putting function in a class is just a very small part of what OOP should be.
Anyway, your problems is that a there are only two way to refere to an class method, either when it is associated with a **specific** object or if it is static in the class (basically associated with the class but not with the objects). In your code you try to treat an object bound function as if it is a static one (I am sure that if you will check your error log you will see some relevant error). There are two possible way to fix it
1. Make the relevant functions static and use the syntax in your second variation
2. use a singleton patter, instantiate an object of the dashboard class, keep it as a global and use it instead of the class name in your first variation. instead of
```
public function setup_dashboard_page() {
My_Dashboard::add_dashboard_page();
}
```
do
```
global $dashboard;
$dashboard = new my_dashboard()
.....
public function setup_dashboard_page() {
global $dashboard;
$dashboard->add_dashboard_page();
}
```
And always debug code with full error reporting and fix all errors and notices ;)
|
200,468 |
<p>I am trying to learn WP theme development. And I just learned that WP already has a jQuery version included. Until now I have been using the jQuery from Google's CDN. </p>
<p>So I just now deleted the CDN link from my code. And of course all my jQuery code stopped working. </p>
<p>So I guess I am missing something. What do I need to do if I want to use WordPress's local jQuery?</p>
<p>When I search SE QA and Google all I can find is how to un-register the local jQuery version and then register CDN. But that is not what I want to do. I want to use the local jQuery.</p>
<p>So what am I missing?</p>
|
[
{
"answer_id": 200470,
"author": "Ignat B.",
"author_id": 38121,
"author_profile": "https://wordpress.stackexchange.com/users/38121",
"pm_score": 1,
"selected": false,
"text": "<p>In order to enqueue jQuery from WP-installation you can:</p>\n\n<pre><code>function custom_enqueue_scripts() {\n // Jquery enqueue\n wp_enqueue_script('jquery');\n}\n\nadd_action('wp_enqueue_scripts', 'custom_enqueue_scripts');\n</code></pre>\n\n<p>Additionally, using this trick you can enqueue jQuery into footer (<code>wp_footer</code>) </p>\n\n<pre><code>function custom_enqueue_scripts() {\n // Jquery - to the footer of template\n wp_deregister_script('jquery');\n wp_register_script('jquery', includes_url('/js/jquery/jquery.js'), false, NULL, true);\n wp_enqueue_script('jquery');\n}\n\nadd_action('wp_enqueue_scripts', 'custom_enqueue_scripts');\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Expanding the answer. </p>\n\n<p>Using <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_script\" rel=\"nofollow noreferrer\"><code>wp_register_script</code></a> you can register your custom scripts. After, they can be <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script</code></a> by the <code>$handler</code>. </p>\n\n<p>Generally it grant a benefit of code length reduction <a href=\"https://wordpress.stackexchange.com/questions/82490/when-should-i-use-wp-register-script-with-wp-enqueue-script-vs-just-wp-enque\">[Related Answer]</a>, but I'd like to emphasize your attention on WordPress pre-registered scripts (local in your meaning). </p>\n\n<p>Visit this Codex Page <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_script#Handles_and_Their_Script_Paths_Registered_by_WordPress\" rel=\"nofollow noreferrer\">[Handles and Their Script Paths Registered by WordPress]</a>. There you will find a <code>$handler</code>'s for jQuery UI and other usefull stuff, that you can enqueue as on example above.</p>\n"
},
{
"answer_id": 200471,
"author": "totels",
"author_id": 23446,
"author_profile": "https://wordpress.stackexchange.com/users/23446",
"pm_score": 3,
"selected": true,
"text": "<p>WP's jQuery is not mapped to <code>$</code> like you may expect, it is loaded in <code>noConflict</code> mode so you'll need to use <code>jQuery()</code> instead of <code>$()</code>, unless you map it yourself.</p>\n\n<p>When you include your js file you'll want to make sure to set jQuery as a dependency as well:</p>\n\n<pre><code>wp_enqueue_script( 'your-script-handle', get_stylesheet_directory_uri() . '/js/your-script.js', array( 'jquery' ), '1.0.0' );\n</code></pre>\n"
}
] |
2015/09/02
|
[
"https://wordpress.stackexchange.com/questions/200468",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66256/"
] |
I am trying to learn WP theme development. And I just learned that WP already has a jQuery version included. Until now I have been using the jQuery from Google's CDN.
So I just now deleted the CDN link from my code. And of course all my jQuery code stopped working.
So I guess I am missing something. What do I need to do if I want to use WordPress's local jQuery?
When I search SE QA and Google all I can find is how to un-register the local jQuery version and then register CDN. But that is not what I want to do. I want to use the local jQuery.
So what am I missing?
|
WP's jQuery is not mapped to `$` like you may expect, it is loaded in `noConflict` mode so you'll need to use `jQuery()` instead of `$()`, unless you map it yourself.
When you include your js file you'll want to make sure to set jQuery as a dependency as well:
```
wp_enqueue_script( 'your-script-handle', get_stylesheet_directory_uri() . '/js/your-script.js', array( 'jquery' ), '1.0.0' );
```
|
200,469 |
<p>After WordPress 4.3, the old method of disabling wpautop no longer works. Has anyone discovered a new method for removing this function?</p>
<pre><code>remove_filter( 'the_content', 'wpautop', 99 );
remove_filter( 'the_excerpt', 'wpautop', 99 );
</code></pre>
|
[
{
"answer_id": 201896,
"author": "denis.stoyanov",
"author_id": 76287,
"author_profile": "https://wordpress.stackexchange.com/users/76287",
"pm_score": 3,
"selected": false,
"text": "<p>I guess you don't use it at all, so why don't you just remove the filter?</p>\n\n<pre><code>remove_filter('the_content', 'wpautop');\nremove_filter('the_excerpt', 'wpautop');\n</code></pre>\n\n<p>I've tested it a few minutes ago (on WP 4.3) and it works.</p>\n\n<p>p.s. I just saw that you use the same function. Sorry for that. What version are you using? This disables the wpautop on 4.3. </p>\n"
},
{
"answer_id": 201915,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 3,
"selected": false,
"text": "<p>On the javascript side, as a crude measure you could just replace the <code>wp.editor.autop</code> and <code>wp.editor.removep</code> with no ops:</p>\n\n<pre><code>add_action( 'admin_print_footer_scripts', function () {\n ?>\n <script type=\"text/javascript\">\n jQuery(function ($) {\n if (typeof wp === 'object' && typeof wp.editor === 'object') {\n wp.editor.autop = function (text) { return text; };\n wp.editor.removep = function (text) { return text; };\n }\n });\n </script>\n <?php\n}, 100 );\n</code></pre>\n\n<p>However on very limited testing although it seems to keep markup it does put it all on one line in the Text editor, which is pretty ugly...</p>\n"
},
{
"answer_id": 359091,
"author": "NJENGAH",
"author_id": 67761,
"author_profile": "https://wordpress.stackexchange.com/users/67761",
"pm_score": 1,
"selected": false,
"text": "<p>This works well. It's about the priority of the hook :</p>\n\n<pre><code>add_filter( 'the_content', 'njengah_remove_autop', 0 );\n\nfunction njengah_remove_autop($content) {\n\n // remove autop \n\n remove_filter( 'the_content', 'wpautop' );\n\n\n return $content;\n}\n</code></pre>\n"
}
] |
2015/09/02
|
[
"https://wordpress.stackexchange.com/questions/200469",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78759/"
] |
After WordPress 4.3, the old method of disabling wpautop no longer works. Has anyone discovered a new method for removing this function?
```
remove_filter( 'the_content', 'wpautop', 99 );
remove_filter( 'the_excerpt', 'wpautop', 99 );
```
|
I guess you don't use it at all, so why don't you just remove the filter?
```
remove_filter('the_content', 'wpautop');
remove_filter('the_excerpt', 'wpautop');
```
I've tested it a few minutes ago (on WP 4.3) and it works.
p.s. I just saw that you use the same function. Sorry for that. What version are you using? This disables the wpautop on 4.3.
|
200,505 |
<p>I am working on a custom query to show a few posts. I am able to output all the post ID's. I am trying to turn these ID's into an array so I can use 'post__in' => $myarray in my query. How can I do this?</p>
<pre><code> <?php
$allposts = $wpdb->get_results("SELECT `music_id` FROM `custom_table` ORDER BY id DESC LIMIT 5");
foreach ($allposts as $singlepost) {
echo '<p>' .$singlepost->music_id. '</p>';
}
?>
</code></pre>
|
[
{
"answer_id": 200488,
"author": "Robert Rome",
"author_id": 78655,
"author_profile": "https://wordpress.stackexchange.com/users/78655",
"pm_score": 0,
"selected": false,
"text": "<p>You want to isolate what changes were made that caused the issue. If there is any way of narrowing down when the problem started - i.e. after what code or plugin changes - that would be my first stop.</p>\n\n<p>If you can't think of any suspects:</p>\n\n<ol>\n<li>Look in your browser's Javascript console and see if an error pops up when you try and publish the post. If so, the source (and type) of the error will hopefully give you a hint about the source of the problem.</li>\n<li>If there are no Javascript errors on publish, you may have an issue on the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow\">save post hook</a>. Have there been any recent code changes using this hook?</li>\n<li>If you recently upgraded Wordpress through a manual process you could have accidentally missed adding/replacing some files in the process.</li>\n</ol>\n\n<p>Still struggling to find the source of the issue?</p>\n\n<ol>\n<li>Check if it's a plugin issue: Disable all your plugins (in a dev environment), and then see if publishing now works properly. If so, it's probably not a plugin issue. If not, gradually re-enable plugins until you find the culprit, paying particular attention to the most recently enabled plugins.</li>\n<li>Check if it's a code issue: If you're on a version control system, roll back until you locate the last commit where the functionality worked, then see what code changes were made in the commit that broke things.</li>\n</ol>\n"
},
{
"answer_id": 202429,
"author": "terraconnect",
"author_id": 80252,
"author_profile": "https://wordpress.stackexchange.com/users/80252",
"pm_score": 2,
"selected": true,
"text": "<p>You are most probably using an outdated version of Advanced Custom Fields plugin. I had the same issue. Updating to latest version fixed the issue.</p>\n"
}
] |
2015/09/02
|
[
"https://wordpress.stackexchange.com/questions/200505",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/49017/"
] |
I am working on a custom query to show a few posts. I am able to output all the post ID's. I am trying to turn these ID's into an array so I can use 'post\_\_in' => $myarray in my query. How can I do this?
```
<?php
$allposts = $wpdb->get_results("SELECT `music_id` FROM `custom_table` ORDER BY id DESC LIMIT 5");
foreach ($allposts as $singlepost) {
echo '<p>' .$singlepost->music_id. '</p>';
}
?>
```
|
You are most probably using an outdated version of Advanced Custom Fields plugin. I had the same issue. Updating to latest version fixed the issue.
|
200,510 |
<p>Using the S2member plugin, a meta_key for the last-payment-time is automatically stored in WordPress DB under table wp_usermeta (custom field is called wp_meds2member_last_payment_time).</p>
<p>From wp_usermeta, the column called meta_key has a value 'wp_meds2member_last_payment_time'. But the content I'm trying to collect is its meta_value equivalent.
<a href="https://i.stack.imgur.com/meDAP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/meDAP.png" alt="The meta_value"></a></p>
<p>I didn't find how to call this meta_value to the function below where I use the date of the last payment time to start a new count of the posts created by the user.</p>
<pre><code>function check_post_limit(){
if(current_user_can('edit_posts')) {
global $userdata;
global $post_type;
global $wpdb;
$postintervall = date('Y-m-d H:i:s', $s2member_last_payment_time );
$item_count = $wpdb->get_var( "SELECT count(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_author = $userdata->ID AND post_date > '$postintervall'" );
if(( $item_count >= 2 ) && (current_user_is("s2member_level1")) )
{ wp_die( 'Do not create too much posts.','check-limit' ); }
return; }
}
</code></pre>
<p>Any suggestions? Thanks</p>
|
[
{
"answer_id": 205090,
"author": "Cristián Lávaque",
"author_id": 81709,
"author_profile": "https://wordpress.stackexchange.com/users/81709",
"pm_score": 0,
"selected": false,
"text": "<p>@Amine, the meta field's name is just <code>s2member_last_payment_time</code>, so try it without the <code>wp_med</code> prefix and see if that works.</p>\n\n<pre><code>$2member_last_payment_time = get_user_meta(get_current_user_id(), 's2member_last_payment_time', true);\n</code></pre>\n\n<p>You can also try s2Member's function <code>get_user_field</code>: <a href=\"http://www.s2member.com/codex/stable/s2member/api_functions/package-functions/#src_doc_get_user_field%28%29\" rel=\"nofollow\">http://www.s2member.com/codex/stable/s2member/api_functions/package-functions/#src_doc_get_user_field%28%29</a></p>\n\n<pre><code>$s2member_last_payment_time = get_user_field ('s2member_last_payment_time');\n</code></pre>\n\n<p>If no payment actually happened, then no payment time would be recorded, but if there is it'll be a timestamp.</p>\n\n<p>I hope that helps. :)</p>\n"
},
{
"answer_id": 205212,
"author": "Amine Richer",
"author_id": 78780,
"author_profile": "https://wordpress.stackexchange.com/users/78780",
"pm_score": 2,
"selected": true,
"text": "<p>@Cristián Lávaque Thank you for the hints ;) </p>\n\n<p>Actually I managed to resolve the issue blocking this function (show the hidden comment above). In case this would help anyone here is the final working code:</p>\n\n<pre><code>function check_post_limit() {\n if ( current_user_can( 'edit_posts' ) ) {\n global $userdata;\n global $wpdb;\n $s2member_last_payment_time = get_user_meta( get_current_user_id(), \n 'wp_s2member_last_payment_time', true );\n $postintervall = date( 'Y-m-d H:i:s', $s2member_last_payment_time );\n $item_count = $wpdb->get_var( \"SELECT count(*) FROM $wpdb->posts \n WHERE post_status = 'publish' AND post_author = $userdata->ID \n AND post_date > '$postintervall'\" );\n if ( ( $item_count >= 2 ) && ( current_user_is( \"s2member_level1\" ) ) ) { \n wp_die( 'Do not create too much posts.', 'check-limit' ); \n }\n return; \n }\n}\n</code></pre>\n"
}
] |
2015/09/02
|
[
"https://wordpress.stackexchange.com/questions/200510",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78780/"
] |
Using the S2member plugin, a meta\_key for the last-payment-time is automatically stored in WordPress DB under table wp\_usermeta (custom field is called wp\_meds2member\_last\_payment\_time).
From wp\_usermeta, the column called meta\_key has a value 'wp\_meds2member\_last\_payment\_time'. But the content I'm trying to collect is its meta\_value equivalent.
[](https://i.stack.imgur.com/meDAP.png)
I didn't find how to call this meta\_value to the function below where I use the date of the last payment time to start a new count of the posts created by the user.
```
function check_post_limit(){
if(current_user_can('edit_posts')) {
global $userdata;
global $post_type;
global $wpdb;
$postintervall = date('Y-m-d H:i:s', $s2member_last_payment_time );
$item_count = $wpdb->get_var( "SELECT count(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_author = $userdata->ID AND post_date > '$postintervall'" );
if(( $item_count >= 2 ) && (current_user_is("s2member_level1")) )
{ wp_die( 'Do not create too much posts.','check-limit' ); }
return; }
}
```
Any suggestions? Thanks
|
@Cristián Lávaque Thank you for the hints ;)
Actually I managed to resolve the issue blocking this function (show the hidden comment above). In case this would help anyone here is the final working code:
```
function check_post_limit() {
if ( current_user_can( 'edit_posts' ) ) {
global $userdata;
global $wpdb;
$s2member_last_payment_time = get_user_meta( get_current_user_id(),
'wp_s2member_last_payment_time', true );
$postintervall = date( 'Y-m-d H:i:s', $s2member_last_payment_time );
$item_count = $wpdb->get_var( "SELECT count(*) FROM $wpdb->posts
WHERE post_status = 'publish' AND post_author = $userdata->ID
AND post_date > '$postintervall'" );
if ( ( $item_count >= 2 ) && ( current_user_is( "s2member_level1" ) ) ) {
wp_die( 'Do not create too much posts.', 'check-limit' );
}
return;
}
}
```
|
200,523 |
<p>Say I have a bunch of posts, some of them have a meta key called "key1" and some of them have a meta key called "key2". But the posts do not have both.</p>
<p>I'd like to create a custom query which retrieves any post that has "key1" or "key2" as a meta key. (not a single post which has both).</p>
<p>After digging around, the closest I've got to (for a single query) was using the meta_query array which allows me to query for posts that have multiple meta keys. However I am looking for posts OF multiple meta keys.. ie: if it has key1 or key2, load up the query.</p>
<p>Aside from the above, the only other way I can seem to query for posts that have either key1 or key2 is to create multiple queries and loops. I'm wondering if there's a cleaner solution. My ideal end-result would be to have the resulting post mixed in with each other and displayed as if it came from a single query. With multiple queries I feel I wont be able to achieve this as I will get the results with key1 first and then the results with key2 afterwards in the next query/loop.</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 200528,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 3,
"selected": true,
"text": "<p>An easy query like the following should work for you:</p>\n\n<pre><code><?php\n$_query = new WP_Query( array(\n 'post_type' => 'post',\n 'posts_per_page' => -1,\n 'post_status' => 'publish',\n 'meta_query' => array(\n 'relation' => 'OR',\n array(\n 'key' => 'key1'\n ),\n array(\n 'key' => 'key2'\n ),\n ),\n ) );\n?>\n</code></pre>\n\n<p>Note the <code>'relation'=>'OR'</code> in <code>meta_query</code>.</p>\n\n<p>More at:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow\">WP_Query - Custom Fields</a></li>\n<li><a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query\" rel=\"nofollow\">WP_Meta_Query</a></li>\n</ul>\n"
},
{
"answer_id": 200575,
"author": "certainstrings",
"author_id": 75979,
"author_profile": "https://wordpress.stackexchange.com/users/75979",
"pm_score": 0,
"selected": false,
"text": "<p>You could try adding a few more checks in your meta_query.</p>\n\n<pre><code>$args = array(\n\n 'post_type' => 'post',\n 'posts_per_page' => 10,\n 'meta_query' => array(\n 'relation' => 'OR',\n array(\n 'relation' => 'AND', // make sure only this key exists by matching parameters\n array(\n 'key' => 'key1',\n 'compare' => 'EXISTS'\n ),\n array(\n 'key' => 'key2',\n 'compare' => 'NOT EXISTS'\n )\n ),\n array(\n 'relation' => 'AND', // check for the opposite here\n array(\n 'key' => 'key2',\n 'compare' => 'EXISTS'\n ),\n array(\n 'key' => 'key1',\n 'compare' => 'NOT EXISTS'\n )\n )\n )\n);\n</code></pre>\n\n<p>This is an <em>ok</em> solution if you're only comparing two meta keys, but it might be cleaner to write a sql query.</p>\n"
}
] |
2015/09/03
|
[
"https://wordpress.stackexchange.com/questions/200523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35675/"
] |
Say I have a bunch of posts, some of them have a meta key called "key1" and some of them have a meta key called "key2". But the posts do not have both.
I'd like to create a custom query which retrieves any post that has "key1" or "key2" as a meta key. (not a single post which has both).
After digging around, the closest I've got to (for a single query) was using the meta\_query array which allows me to query for posts that have multiple meta keys. However I am looking for posts OF multiple meta keys.. ie: if it has key1 or key2, load up the query.
Aside from the above, the only other way I can seem to query for posts that have either key1 or key2 is to create multiple queries and loops. I'm wondering if there's a cleaner solution. My ideal end-result would be to have the resulting post mixed in with each other and displayed as if it came from a single query. With multiple queries I feel I wont be able to achieve this as I will get the results with key1 first and then the results with key2 afterwards in the next query/loop.
Thanks in advance!
|
An easy query like the following should work for you:
```
<?php
$_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'key1'
),
array(
'key' => 'key2'
),
),
) );
?>
```
Note the `'relation'=>'OR'` in `meta_query`.
More at:
* [WP\_Query - Custom Fields](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters)
* [WP\_Meta\_Query](https://codex.wordpress.org/Class_Reference/WP_Meta_Query)
|
200,580 |
<p>I've created a new Wordpress site using the <a href="http://themient.com/themes/realistic" rel="nofollow noreferrer">Realistic theme</a>. I added a logo, and this was the resulting webpage (ignore the sidebar):</p>
<p><img src="https://i.imgur.com/Nyj4Zlh.png" alt="screenshot"></p>
<p>I want the website title to be displayed next to the logo, for which I'd need to edit the header.php file. So, I created a child theme, and this is the result:</p>
<p><img src="https://i.imgur.com/lnIx5N9.png" alt="screenshot"></p>
<p>Note how the footer suddenly behaves like it should (how though? I'm fine with this, however). There's however suddenly a random menu button in the top-left corner (which should only be there in the mobile version of the site) and the menu button on posts is now placed incorrectly. The menu of that button pops up in its old spot though:</p>
<p><img src="https://i.imgur.com/GKEC0R7.png" alt="screenshot"></p>
<p>This is the content of the child theme's function.php:</p>
<pre><code><?php
//
// Recommended way to include parent theme styles.
// (Please see http://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme)
//
function 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',
get_stylesheet_directory_uri() . '/css/fontello.css',
get_stylesheet_directory_uri() . '/css/material-default.min.css',
get_stylesheet_directory_uri() . '/css/material-style1.min.css',
get_stylesheet_directory_uri() . '/css/material-style2.min.css',
get_stylesheet_directory_uri() . '/css/material-style3.min.css',
get_stylesheet_directory_uri() . '/css/material-style4.min.css',
get_stylesheet_directory_uri() . '/css/material-style5.min.css',
array( $parent_style )
);
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
//
// Your code goes below
//
</code></pre>
<p>These are the contents of the child theme's style.css:</p>
<pre><code>/*
Theme Name: Realistic Child
Theme URI: http://themient.com/themes/realistic
Description: Realistic Child Theme
Author: Asmi Khalil
Author URI: http://themient.com
Template: realistic
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: Blue, Red, Purple, two-columns, left-sidebar, right-sidebar, fixed-layout, responsive-layout, accessibility-ready, custom-background, custom-colors, custom-menu, editor-style, featured-images, microformats, post-formats, sticky-post, threaded-comments, translation-ready
Text Domain: realistic
*/
</code></pre>
<p>How can I fix this, preferably keeping the child theme's footer down below where it belongs?</p>
|
[
{
"answer_id": 200590,
"author": "RooWM",
"author_id": 18563,
"author_profile": "https://wordpress.stackexchange.com/users/18563",
"pm_score": 0,
"selected": false,
"text": "<p>Are all of those style-sheets included from the parent theme?</p>\n\n<p>If so? Try <code>get_template_directory_uri()</code> instead of <code>get_stylesheet_directory_uri()</code></p>\n\n<p>Rule of thumb: if the style sheet you're trying to enqueue is in your child theme directory use, <code>get_stylesheet_directory_uri()</code> if it is in the parent theme's directory use <code>get_template_directory_uri()</code></p>\n"
},
{
"answer_id": 200595,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 0,
"selected": false,
"text": "<p>It's quite possible that critical styles (and other elements, too) are being derived from other sources and locations than separate CSS files. Many \"advanced\" themes (and plug-ins) will do this kind of thing: It can be annoying for developers, but is often pursued for the sake of making customization easier for non-developers (who wouldn't be using child themes). </p>\n\n<p>I'd recommend that you use Firebug, Inspect Element, or other tool to determine where the formatting is actually originating. The results will often show up as \"element\" styles. Other times they may (seem to) refer you to your installation's root directory. They may show up in the page source as sent directly to the header (between <code><style></code> tags). You might also find clues regarding an unexpected origin of the element itself. </p>\n\n<p>You might also check your theme options page for indications as to where and how theme-specific styles are being set and sent. You may also have to delve into the theme's template structure if it uses a \"tags\" file. </p>\n"
},
{
"answer_id": 200628,
"author": "Tanno",
"author_id": 78824,
"author_profile": "https://wordpress.stackexchange.com/users/78824",
"pm_score": 2,
"selected": true,
"text": "<p>I decided to work with the creator of the theme, and the problem has been fixed!</p>\n\n<p>I did the following:</p>\n\n<ol>\n<li>Remove all code from the child theme's function.php, leaving it empty.</li>\n<li>Replaced the child theme's style.css with a copy of the parent theme's style.css, and replaced the commented bit with the child theme's commented bit.</li>\n</ol>\n\n<p>This fixed all problems. Thanks to everyone for your help.</p>\n"
}
] |
2015/09/03
|
[
"https://wordpress.stackexchange.com/questions/200580",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78824/"
] |
I've created a new Wordpress site using the [Realistic theme](http://themient.com/themes/realistic). I added a logo, and this was the resulting webpage (ignore the sidebar):

I want the website title to be displayed next to the logo, for which I'd need to edit the header.php file. So, I created a child theme, and this is the result:

Note how the footer suddenly behaves like it should (how though? I'm fine with this, however). There's however suddenly a random menu button in the top-left corner (which should only be there in the mobile version of the site) and the menu button on posts is now placed incorrectly. The menu of that button pops up in its old spot though:

This is the content of the child theme's function.php:
```
<?php
//
// Recommended way to include parent theme styles.
// (Please see http://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme)
//
function 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',
get_stylesheet_directory_uri() . '/css/fontello.css',
get_stylesheet_directory_uri() . '/css/material-default.min.css',
get_stylesheet_directory_uri() . '/css/material-style1.min.css',
get_stylesheet_directory_uri() . '/css/material-style2.min.css',
get_stylesheet_directory_uri() . '/css/material-style3.min.css',
get_stylesheet_directory_uri() . '/css/material-style4.min.css',
get_stylesheet_directory_uri() . '/css/material-style5.min.css',
array( $parent_style )
);
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
//
// Your code goes below
//
```
These are the contents of the child theme's style.css:
```
/*
Theme Name: Realistic Child
Theme URI: http://themient.com/themes/realistic
Description: Realistic Child Theme
Author: Asmi Khalil
Author URI: http://themient.com
Template: realistic
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: Blue, Red, Purple, two-columns, left-sidebar, right-sidebar, fixed-layout, responsive-layout, accessibility-ready, custom-background, custom-colors, custom-menu, editor-style, featured-images, microformats, post-formats, sticky-post, threaded-comments, translation-ready
Text Domain: realistic
*/
```
How can I fix this, preferably keeping the child theme's footer down below where it belongs?
|
I decided to work with the creator of the theme, and the problem has been fixed!
I did the following:
1. Remove all code from the child theme's function.php, leaving it empty.
2. Replaced the child theme's style.css with a copy of the parent theme's style.css, and replaced the commented bit with the child theme's commented bit.
This fixed all problems. Thanks to everyone for your help.
|
200,586 |
<p>I want to put the variable in the shortcode, but it is not working. What i have done wrong.</p>
<pre><code><?php $calendar = getCalendarTag();?>
<?php echo do_shortcode( '[ai1ec tag_name=".$calendar."]"]' ) ?>
</code></pre>
|
[
{
"answer_id": 200594,
"author": "gdaniel",
"author_id": 30984,
"author_profile": "https://wordpress.stackexchange.com/users/30984",
"pm_score": 2,
"selected": false,
"text": "<p>Try changing your code to:</p>\n\n<pre><code><?php echo do_shortcode('[ai1ec tag_name=\"' . $calendar . '\"]'); ?>\n</code></pre>\n"
},
{
"answer_id": 361504,
"author": "Asha",
"author_id": 92824,
"author_profile": "https://wordpress.stackexchange.com/users/92824",
"pm_score": 0,
"selected": false,
"text": "<pre><code> $val= $options['c_form'];\n echo do_shortcode(\"$val\");\n</code></pre>\n"
},
{
"answer_id": 378499,
"author": "Muhammad Rizwan",
"author_id": 197825,
"author_profile": "https://wordpress.stackexchange.com/users/197825",
"pm_score": 1,
"selected": false,
"text": "<p>Just use this line of code if you store shortcode in a variable:</p>\n<pre><code><?php\n $contact_popup_form = '[contact-form-7 id="91" title="Contact form"]';\n echo do_shortcode($contact_popup_form);\n?>\n</code></pre>\n"
}
] |
2015/09/03
|
[
"https://wordpress.stackexchange.com/questions/200586",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78832/"
] |
I want to put the variable in the shortcode, but it is not working. What i have done wrong.
```
<?php $calendar = getCalendarTag();?>
<?php echo do_shortcode( '[ai1ec tag_name=".$calendar."]"]' ) ?>
```
|
Try changing your code to:
```
<?php echo do_shortcode('[ai1ec tag_name="' . $calendar . '"]'); ?>
```
|
200,622 |
<p>Tried to find an or some hook to fire a function when theme is being delited, but didn't find any hook..</p>
<p>May be someone can tell if there's a way to fire my function on themes delete event?</p>
<p>I need it to delete options and drop tables on theme delete. ( for example )</p>
<p>Plugins do have <code>uninstall.php</code> or <code>register_uninstall_hook()</code>.</p>
<p>Need same for themes! any help ?</p>
<p>My thoughts so far:</p>
<ol>
<li><p>create <code>new WP_Filesystem_$module</code> class and force WP to use my <code>WP_Filesystem_$module</code> class for deleting themes, where i can insert custom actions atc.</p></li>
<li><p>insert custom action in <code>deleted_site_transient</code> action, checking if it was <code>update_themes</code> transient and check if theme was delited, wich theme was deleted etc..</p></li>
</ol>
<p>Both methods has different questions like how to force my class or how to check wich theme was deleted in <code>deleted_site_transient</code>...</p>
<p>What's your thoughts on these ?</p>
|
[
{
"answer_id": 230140,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>As long as you don't delete your theme by ftp, but use the regular way of switching to another theme in the admin, there is a hook to use, <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/switch_theme\" rel=\"nofollow\"><code>switch_theme</code></a>. It works like this:</p>\n\n<pre><code>add_action('switch_theme', 'mytheme_setup_options');\n\nfunction mytheme_setup_options () {\n delete_option('mytheme_option1');\n delete_option('mytheme_option2');\n}\n</code></pre>\n\n<p>There's a sister hook called <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme\" rel=\"nofollow\"><code>after_switch_theme</code></a>, which you could use, for instance, to load default options when a theme is switched on.</p>\n"
},
{
"answer_id": 411358,
"author": "RafaSashi",
"author_id": 37412,
"author_profile": "https://wordpress.stackexchange.com/users/37412",
"pm_score": 1,
"selected": false,
"text": "<p>Since 5.8.0 you can use the <code>deleted_theme</code> hook together with the stylesheet name:</p>\n<pre><code>add_action('deleted_theme', function($stylesheet, $deleted){\n \n // do something\n});\n</code></pre>\n<p>You will have to run this filter from outside the theme that you are trying to delete. In the OP case since it is for a plugin it should work.</p>\n<p><strong>Resources</strong></p>\n<p><a href=\"https://github.com/WordPress/WordPress/blob/748a5d9919986a6281df4e44d176501b29483450/wp-admin/includes/theme.php#L96\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/748a5d9919986a6281df4e44d176501b29483450/wp-admin/includes/theme.php#L96</a></p>\n"
}
] |
2015/09/03
|
[
"https://wordpress.stackexchange.com/questions/200622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38034/"
] |
Tried to find an or some hook to fire a function when theme is being delited, but didn't find any hook..
May be someone can tell if there's a way to fire my function on themes delete event?
I need it to delete options and drop tables on theme delete. ( for example )
Plugins do have `uninstall.php` or `register_uninstall_hook()`.
Need same for themes! any help ?
My thoughts so far:
1. create `new WP_Filesystem_$module` class and force WP to use my `WP_Filesystem_$module` class for deleting themes, where i can insert custom actions atc.
2. insert custom action in `deleted_site_transient` action, checking if it was `update_themes` transient and check if theme was delited, wich theme was deleted etc..
Both methods has different questions like how to force my class or how to check wich theme was deleted in `deleted_site_transient`...
What's your thoughts on these ?
|
Since 5.8.0 you can use the `deleted_theme` hook together with the stylesheet name:
```
add_action('deleted_theme', function($stylesheet, $deleted){
// do something
});
```
You will have to run this filter from outside the theme that you are trying to delete. In the OP case since it is for a plugin it should work.
**Resources**
<https://github.com/WordPress/WordPress/blob/748a5d9919986a6281df4e44d176501b29483450/wp-admin/includes/theme.php#L96>
|
201,638 |
<p>Based on a few references I've built a function to output a list of custom taxonomy terms separated by comma. The code works as intended, where <code>food_tag</code> is the custom taxonomy I registered for a custom post_type.</p>
<p>Here's the function:</p>
<pre><code>function get_taxonomy_food_tags(){
$terms = get_terms('food_tag');
foreach($terms as $term){
// The $term is an object, so we don't need to specify the $taxonomy.
$term_link = get_term_link($term);
$numItems = count($terms);
$i = 0;
// If there was an error, continue to the next term.
if (is_wp_error($term_link)){
continue;
}
// We successfully got a link. Print it out.
echo '<a href="' . esc_url($term_link) . '">' . $term->name . '</a>';
if (++$i != $numItems) {
echo ', ';
}
}
}
</code></pre>
<p>I then place the code <code><?php get_taxonony_food_tags(); ?></code> anywhere in my theme's .php templates and I get a list of my custom tags with a link. such as:</p>
<p><strong>Ingredients: Bacon, Tomato Slices, Tomato Sauce, Lettuce, Beef,</strong></p>
<p>It turns out the last tag in the array is also printed with a comma</p>
<p>How do I properly set up the function to exclude the last comma?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 201652,
"author": "Eduardo Sánchez Hidalgo Urías",
"author_id": 72745,
"author_profile": "https://wordpress.stackexchange.com/users/72745",
"pm_score": 1,
"selected": false,
"text": "<p>The problem is you are giving 0 as a value to $i, every time the foreach loop executes, so, when the last if statement executes, every time the comparison is 1 != 3, and the comma will always be printed. Try to declare $i = 0; outside the foreach loop. Like this:</p>\n\n<pre><code>$terms = get_terms('food_tag');\n$i = 0;\nforeach($terms as $term){ \n\n//the code here\n\n}\n</code></pre>\n\n<p>Also, there is a curly bracket missing at the end, maybe thats only a copy paste error, but for those who try to copy paste this and make it run. </p>\n"
},
{
"answer_id": 201654,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>You have a couple of flaws here:</p>\n<ul>\n<li><p><strong>ALWAYS</strong> code in a way with a mindset of that your code <strong>will</strong> fail. This is very important. Most people code with a perfect world mindset. A perfect world will never happen. Always think of what will happen when your code fail.</p>\n<p>As example, in your code, <code>$terms</code> return an object of term objects if everything pans out. <code>$terms</code> also returns an empty array if there are no terms in the taxonomy or terms without having any posts. It also returns a <code>WP_Error</code> object if the taxonomy does not exist. This is all bugs. Invalid taxonomy you may ask. If you have correctly registered your taxonomy in a plugin, and you disable that plugin, your taxonomy does not exist anymore, which will trigger the invalid taxonomy error.</p>\n</li>\n<li><p>You should start your counter outside your <code>foreach</code> loop. Not inside</p>\n</li>\n<li><p>The <code>get_</code> prefix is used for functions that returns its output, not echo it.</p>\n</li>\n<li><p><strong>Always</strong> sanitize and validate</p>\n</li>\n</ul>\n<p>I will rewrite your code to look something like this: (<em><strong>NOTE:</strong> Requires PHP5.4 +</em>)</p>\n<pre><code>function get_taxonomy_food_tags( $taxonomy = '', $args = [] )\n{\n // Check if we have a taxonomy and that it is valid. If not, return false\n if ( !$taxonomy )\n return false;\n\n // Sanitize the taxonomy input\n $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );\n\n if ( !taxonomy_exists( $taxonomy ) )\n return false;\n\n // If we reached this point, our taxonomy is valid. So lets continue. Get our terms\n $terms = get_terms( $taxonomy, $args );\n\n // We will only check if we have terms, we know our taxonomy is valid because we have reached this point\n if ( empty( $terms ) )\n return false;\n\n // Great, if we got to this point, we have terms, lets continue\n // Define our variable to hold our term links\n $term_links_array = [];\n foreach ( $terms as $term ) {\n $term_link = get_term_link( $term );\n\n // Make sure we do not have a WP_Error object, not really necessary, but better be safe\n if ( is_wp_error( $term ) )\n continue;\n\n // Build an array of term links. Let php do the hard work and calculations\n $term_links_array[] = '<a href="' . esc_url($term_link) . '">' . $term->name . '</a>';\n } // endforeach\n\n // Make sure that we have an array of term links, if not, return false\n if ( !$term_links_array )\n return false;\n\n // We have reached this point, lets output our term links\n return implode( ', ', $term_links_array );\n}\n</code></pre>\n<p>You can now use it as follow</p>\n<pre><code>echo get_taxonomy_food_tags( 'food_tag' );\n</code></pre>\n<p>I have also introduced a second parameter which you can use to pass an array of arguments to the internal <code>get_terms()</code> function, so you can use the new function in the same exact way as the default <code>get_terms()</code> function</p>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201638",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45893/"
] |
Based on a few references I've built a function to output a list of custom taxonomy terms separated by comma. The code works as intended, where `food_tag` is the custom taxonomy I registered for a custom post\_type.
Here's the function:
```
function get_taxonomy_food_tags(){
$terms = get_terms('food_tag');
foreach($terms as $term){
// The $term is an object, so we don't need to specify the $taxonomy.
$term_link = get_term_link($term);
$numItems = count($terms);
$i = 0;
// If there was an error, continue to the next term.
if (is_wp_error($term_link)){
continue;
}
// We successfully got a link. Print it out.
echo '<a href="' . esc_url($term_link) . '">' . $term->name . '</a>';
if (++$i != $numItems) {
echo ', ';
}
}
}
```
I then place the code `<?php get_taxonony_food_tags(); ?>` anywhere in my theme's .php templates and I get a list of my custom tags with a link. such as:
**Ingredients: Bacon, Tomato Slices, Tomato Sauce, Lettuce, Beef,**
It turns out the last tag in the array is also printed with a comma
How do I properly set up the function to exclude the last comma?
Thanks in advance.
|
You have a couple of flaws here:
* **ALWAYS** code in a way with a mindset of that your code **will** fail. This is very important. Most people code with a perfect world mindset. A perfect world will never happen. Always think of what will happen when your code fail.
As example, in your code, `$terms` return an object of term objects if everything pans out. `$terms` also returns an empty array if there are no terms in the taxonomy or terms without having any posts. It also returns a `WP_Error` object if the taxonomy does not exist. This is all bugs. Invalid taxonomy you may ask. If you have correctly registered your taxonomy in a plugin, and you disable that plugin, your taxonomy does not exist anymore, which will trigger the invalid taxonomy error.
* You should start your counter outside your `foreach` loop. Not inside
* The `get_` prefix is used for functions that returns its output, not echo it.
* **Always** sanitize and validate
I will rewrite your code to look something like this: (***NOTE:** Requires PHP5.4 +*)
```
function get_taxonomy_food_tags( $taxonomy = '', $args = [] )
{
// Check if we have a taxonomy and that it is valid. If not, return false
if ( !$taxonomy )
return false;
// Sanitize the taxonomy input
$taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
if ( !taxonomy_exists( $taxonomy ) )
return false;
// If we reached this point, our taxonomy is valid. So lets continue. Get our terms
$terms = get_terms( $taxonomy, $args );
// We will only check if we have terms, we know our taxonomy is valid because we have reached this point
if ( empty( $terms ) )
return false;
// Great, if we got to this point, we have terms, lets continue
// Define our variable to hold our term links
$term_links_array = [];
foreach ( $terms as $term ) {
$term_link = get_term_link( $term );
// Make sure we do not have a WP_Error object, not really necessary, but better be safe
if ( is_wp_error( $term ) )
continue;
// Build an array of term links. Let php do the hard work and calculations
$term_links_array[] = '<a href="' . esc_url($term_link) . '">' . $term->name . '</a>';
} // endforeach
// Make sure that we have an array of term links, if not, return false
if ( !$term_links_array )
return false;
// We have reached this point, lets output our term links
return implode( ', ', $term_links_array );
}
```
You can now use it as follow
```
echo get_taxonomy_food_tags( 'food_tag' );
```
I have also introduced a second parameter which you can use to pass an array of arguments to the internal `get_terms()` function, so you can use the new function in the same exact way as the default `get_terms()` function
|
201,657 |
<p>How can I get all the posts from a specific custom post type with WP REST API (either v1 or v2)? I'm very new to this and trying to understand how to do that.</p>
<p>I am currently using WP REST API v2 and managed to fetch a list of all the post types with this</p>
<pre><code>http://domain.com/wp-json/wp/v2/types
</code></pre>
<p>and then managed to get the post type I'm interested in with</p>
<pre><code>http://domain.com/wp-json/wp/v2/types/the-icons-update
</code></pre>
<p>How do I get all the posts from that specific content type?</p>
<p>I have tried with</p>
<pre><code>http://domain.com/wp-json/wp/v2/posts?filter[post_type]=the-icons-update
</code></pre>
<p>But it returns an empty array (I suppose it returns the default posts and on my site there are only posts inside the custom post type I'm trying to retrieve).</p>
<p>Could there be an issue with how I registered the post type?</p>
<pre><code>function custom_post_type() {
$labels = array(
'name' => _x( 'The Icons Update', 'post type general name' ),
'singular_name' => _x( 'The Icons Update', 'post type singular name' ),
'add_new' => _x( 'Add Page', 'magazine' ),
'add_new_item' => __( 'Add New Page' ),
'edit_item' => __( 'Edit Page' ),
'new_item' => __( 'New Page' ),
'all_items' => __( 'All Pages' ),
'view_item' => __( 'View Page' ),
'search_items' => __( 'Search Pages' ),
'not_found' => __( 'No Page found' ),
'not_found_in_trash' => __( 'No Page found in the Trash' ),
'parent_item_colon' => '',
'menu_icon' => '',
'menu_name' => 'The Icons Update'
);
$args = array(
'labels' => $labels,
'description' => 'Holds our projects and project specific data',
'public' => true,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ),
'has_archive' => true,
'taxonomies' => array('post_tag', 'category'),
'hierarchical' => false,
'query_var' => true,
'queryable' => true,
'searchable' => true,
'rewrite' => array( 'slug' => 'the-icons-update' )
);
register_post_type( 'magazine', $args );
flush_rewrite_rules();
}
add_action( 'init', 'custom_post_type' );
</code></pre>
<p>Any help with this is really appreciated.</p>
|
[
{
"answer_id": 201658,
"author": "dev",
"author_id": 79859,
"author_profile": "https://wordpress.stackexchange.com/users/79859",
"pm_score": -1,
"selected": false,
"text": "<p>You should use this:-</p>\n\n<pre><code>http://domain.com/wp-json/wp/v2/posts?job-type=your-post-type \n</code></pre>\n\n<p>Hope it works :)</p>\n"
},
{
"answer_id": 201664,
"author": "dev",
"author_id": 79859,
"author_profile": "https://wordpress.stackexchange.com/users/79859",
"pm_score": 1,
"selected": false,
"text": "<p>Ok here is my complete answer:-</p>\n\n<pre><code>function prefix_register_post_type()\n{\n register_post_type(\n 'prefix_portfolio',\n array(\n 'labels' => array(\n 'name' => __('Portfolio', 'text_domain'),\n 'singular_name' => __('Portfolio', 'text_domain'),\n 'menu_name' => __('Portfolio', 'text_domain'),\n 'name_admin_bar' => __('Portfolio Item', 'text_domain'),\n 'all_items' => __('All Items', 'text_domain'),\n 'add_new' => _x('Add New', 'prefix_portfolio', 'text_domain'),\n 'add_new_item' => __('Add New Item', 'text_domain'),\n 'edit_item' => __('Edit Item', 'text_domain'),\n 'new_item' => __('New Item', 'text_domain'),\n 'view_item' => __('View Item', 'text_domain'),\n 'search_items' => __('Search Items', 'text_domain'),\n 'not_found' => __('No items found.', 'text_domain'),\n 'not_found_in_trash' => __('No items found in Trash.', 'text_domain'),\n 'parent_item_colon' => __('Parent Items:', 'text_domain'),\n ),\n 'public' => true,\n 'menu_position' => 5,\n 'supports' => array(\n 'title',\n 'editor',\n 'thumbnail',\n 'excerpt',\n 'custom-fields',\n ),\n 'taxonomies' => array(\n 'prefix_portfolio_categories',\n ),\n 'has_archive' => true,\n 'rewrite' => array(\n 'slug' => 'portfolio',\n ),\n )\n );\n}\n\nadd_action('init', 'prefix_register_post_type');\n\n\nfunction prefix_register_taxonomy()\n{\n register_taxonomy(\n 'prefix_portfolio_categories',\n array(\n 'prefix_portfolio',\n ),\n array(\n 'labels' => array(\n 'name' => _x('Categories', 'prefix_portfolio', 'text_domain'),\n 'singular_name' => _x('Category', 'prefix_portfolio', 'text_domain'),\n 'menu_name' => __('Categories', 'text_domain'),\n 'all_items' => __('All Categories', 'text_domain'),\n 'edit_item' => __('Edit Category', 'text_domain'),\n 'view_item' => __('View Category', 'text_domain'),\n 'update_item' => __('Update Category', 'text_domain'),\n 'add_new_item' => __('Add New Category', 'text_domain'),\n 'new_item_name' => __('New Category Name', 'text_domain'),\n 'parent_item' => __('Parent Category', 'text_domain'),\n 'parent_item_colon' => __('Parent Category:', 'text_domain'),\n 'search_items' => __('Search Categories', 'text_domain'),\n ),\n 'show_admin_column' => true,\n 'hierarchical' => true,\n 'rewrite' => array(\n 'slug' => 'portfolio/category',\n ),\n )\n );\n}\n\nadd_action('init', 'prefix_register_taxonomy', 0);\n</code></pre>\n\n<p>You should also register taxonomy while registering custom post.</p>\n\n<p>After this the request would be:</p>\n\n<pre><code>wp-json/wp/v2/posts/?taxonomy=prefix_portfolio_categories'&term=your-any-category\n</code></pre>\n\n<p>Hope this may help you :)</p>\n"
},
{
"answer_id": 201973,
"author": "Dioni Mercado",
"author_id": 80038,
"author_profile": "https://wordpress.stackexchange.com/users/80038",
"pm_score": 5,
"selected": false,
"text": "<p>Just add the next parmater into the function register_post_type, it can be before 'menu_position'parameter. 'show_in_rest' => true</p>\n\n<p><a href=\"https://i.stack.imgur.com/fSCOE.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/fSCOE.png\" alt=\"enter image description here\"></a></p>\n\n<p>if you're using a plugin to register your posttype you can use the next code:</p>\n\n<pre><code>add_action( 'init', 'add_anuncios_to_json_api', 30 );\nfunction add_anuncios_to_json_api(){\n global $wp_post_types;\n $wp_post_types['anuncio']->show_in_rest = true;\n}\n</code></pre>\n\n<p>after that, you'll be able to list your posts from mydomain.com/wp-json/wp/v2/posttype_slug</p>\n\n<p>in my case: mydomain.com/wp-json/wp/v2/anuncio</p>\n\n<p>you can also register a new base using the next code:</p>\n\n<pre><code>add_action( 'init', 'add_anuncios_to_json_api', 30 );\nfunction add_anuncios_to_json_api(){\n global $wp_post_types;\n $wp_post_types['anuncio']->show_in_rest = true;\n $wp_post_types['anuncio']->rest_base = 'clasi';\n $wp_post_types['anuncio']->rest_controller_class = 'WP_REST_Posts_Controller';\n}\n</code></pre>\n\n<p>just replace <code>anuncio</code> for your post type slug and 'clasi' will be your route. mydomain.com/wp-json/wp/v2/clasi</p>\n"
},
{
"answer_id": 203305,
"author": "kabisote",
"author_id": 80733,
"author_profile": "https://wordpress.stackexchange.com/users/80733",
"pm_score": 3,
"selected": false,
"text": "<p>To show custom post types in version 2, you need to add <code>'show_in_rest' => true</code> in the register_post_type function arguments, then your posts with that custom post type will be available at the endpoint: <em>wp-json/wp/v2/your-custom-post-type</em>.</p>\n\n<p>Source: <a href=\"http://scottbolinger.com/custom-post-types-wp-api-v2/\" rel=\"noreferrer\">http://scottbolinger.com/custom-post-types-wp-api-v2/</a></p>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201657",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74398/"
] |
How can I get all the posts from a specific custom post type with WP REST API (either v1 or v2)? I'm very new to this and trying to understand how to do that.
I am currently using WP REST API v2 and managed to fetch a list of all the post types with this
```
http://domain.com/wp-json/wp/v2/types
```
and then managed to get the post type I'm interested in with
```
http://domain.com/wp-json/wp/v2/types/the-icons-update
```
How do I get all the posts from that specific content type?
I have tried with
```
http://domain.com/wp-json/wp/v2/posts?filter[post_type]=the-icons-update
```
But it returns an empty array (I suppose it returns the default posts and on my site there are only posts inside the custom post type I'm trying to retrieve).
Could there be an issue with how I registered the post type?
```
function custom_post_type() {
$labels = array(
'name' => _x( 'The Icons Update', 'post type general name' ),
'singular_name' => _x( 'The Icons Update', 'post type singular name' ),
'add_new' => _x( 'Add Page', 'magazine' ),
'add_new_item' => __( 'Add New Page' ),
'edit_item' => __( 'Edit Page' ),
'new_item' => __( 'New Page' ),
'all_items' => __( 'All Pages' ),
'view_item' => __( 'View Page' ),
'search_items' => __( 'Search Pages' ),
'not_found' => __( 'No Page found' ),
'not_found_in_trash' => __( 'No Page found in the Trash' ),
'parent_item_colon' => '',
'menu_icon' => '',
'menu_name' => 'The Icons Update'
);
$args = array(
'labels' => $labels,
'description' => 'Holds our projects and project specific data',
'public' => true,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ),
'has_archive' => true,
'taxonomies' => array('post_tag', 'category'),
'hierarchical' => false,
'query_var' => true,
'queryable' => true,
'searchable' => true,
'rewrite' => array( 'slug' => 'the-icons-update' )
);
register_post_type( 'magazine', $args );
flush_rewrite_rules();
}
add_action( 'init', 'custom_post_type' );
```
Any help with this is really appreciated.
|
Just add the next parmater into the function register\_post\_type, it can be before 'menu\_position'parameter. 'show\_in\_rest' => true
[](https://i.stack.imgur.com/fSCOE.png)
if you're using a plugin to register your posttype you can use the next code:
```
add_action( 'init', 'add_anuncios_to_json_api', 30 );
function add_anuncios_to_json_api(){
global $wp_post_types;
$wp_post_types['anuncio']->show_in_rest = true;
}
```
after that, you'll be able to list your posts from mydomain.com/wp-json/wp/v2/posttype\_slug
in my case: mydomain.com/wp-json/wp/v2/anuncio
you can also register a new base using the next code:
```
add_action( 'init', 'add_anuncios_to_json_api', 30 );
function add_anuncios_to_json_api(){
global $wp_post_types;
$wp_post_types['anuncio']->show_in_rest = true;
$wp_post_types['anuncio']->rest_base = 'clasi';
$wp_post_types['anuncio']->rest_controller_class = 'WP_REST_Posts_Controller';
}
```
just replace `anuncio` for your post type slug and 'clasi' will be your route. mydomain.com/wp-json/wp/v2/clasi
|
201,670 |
<p>If I scheduled a CPU-intensive job via a cron scheduled event, how do I go about stopping it or cancelling the job while it is currently running?</p>
|
[
{
"answer_id": 201690,
"author": "matthew",
"author_id": 52429,
"author_profile": "https://wordpress.stackexchange.com/users/52429",
"pm_score": 2,
"selected": false,
"text": "<p>Removing / un-scheduling obsolete cron jobs can be achieved using this code snippet.</p>\n<pre><code>add_action("init", "remove_cron_job"); \nfunction remove_cron_job() {\n wp_clear_scheduled_hook("my_schedule_hook"); \n} \n</code></pre>\n<p>Change the my_schedule_hook to cron’s hook name and add the code in your theme’s function.php file.</p>\n"
},
{
"answer_id": 373875,
"author": "mattmaldre",
"author_id": 163379,
"author_profile": "https://wordpress.stackexchange.com/users/163379",
"pm_score": 1,
"selected": false,
"text": "<p>You can delete scheduled cron jobs via a SSH command line.\nFirst, take a look at all your active and scheduled cron jobs by doing this command:</p>\n<pre><code>$ wp cron event list\n</code></pre>\n<p>Then you can delete any of the cron jobs by using their hook name. Let's say you have six jobs whose hook name is "crontrol_cron_job". You would run this command:</p>\n<pre><code>$ wp cron event delete crontrol_cron_job\n</code></pre>\n<p>You'll get a result of something like:</p>\n<pre><code>Deleted 6 instances of the cron event 'crontrol_cron_job'.\n</code></pre>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201670",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17642/"
] |
If I scheduled a CPU-intensive job via a cron scheduled event, how do I go about stopping it or cancelling the job while it is currently running?
|
Removing / un-scheduling obsolete cron jobs can be achieved using this code snippet.
```
add_action("init", "remove_cron_job");
function remove_cron_job() {
wp_clear_scheduled_hook("my_schedule_hook");
}
```
Change the my\_schedule\_hook to cron’s hook name and add the code in your theme’s function.php file.
|
201,676 |
<p>hi i am new on WordPress can somebody tell me how can i upload multiple images using wp_handle_upload in a loop </p>
<pre><code>for($i=1;$i<count($_FILES['myfile']['name']);$i++){
$uploadedfile = $_FILES['myfile'].$i;
$upload_overrides = array( 'test_form'.$i => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) ) {
// echo "File is valid, and was successfully uploaded.\n";
$dir_path= $movefile['url'];
} else {
echo $movefile['error'];
}
}//end loop
</code></pre>
|
[
{
"answer_id": 201686,
"author": "dev",
"author_id": 79859,
"author_profile": "https://wordpress.stackexchange.com/users/79859",
"pm_score": 0,
"selected": false,
"text": "<p>Hi here is code I used up in my plugin, hope you understand it and if any problem you can ask me:-</p>\n\n<pre><code>if(isset($_FILES))\n {\n for ($i=1; $i < count($_FILES) ; $i++) \n { \n\n $uploadedfile = $_FILES['question_'.$i];\n ?>\n <script type=\"text/javascript\">\n $(document).ready(function(){\n var nam = <?php echo \"question\".$i; ?>\n var namm = $(\".\"+nam).prev().attr('name');\n\n });\n </script>\n <?php\n\n\n $upload_overrides = array( 'test_form' => false );\n\n $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );\n\n if ( $movefile && !isset( $movefile['error'] ) ) {\n //echo \"File is valid, and was successfully uploaded.\\n\";\n $filename = $movefile['file'];\n } else {\n /**\n * Error generated by _wp_handle_upload()\n * @see _wp_handle_upload() in wp-admin/includes/file.php\n */\n echo $movefile['error'];\n }\n\n // $filename should be the path to a file in the upload directory.\n //$filename = '/path/to/uploads/2013/03/filename.jpg';\n\n\n // Get the path to the upload directory.\n $wp_upload_dir = wp_upload_dir();\n\n $url = $wp_upload_dir['url'] . '/' . basename( $filename );\n echo $url.\"<br>\";\n\n } \n }\n</code></pre>\n\n<p>Here is my html code:-</p>\n\n<pre><code> $question =get_post_meta($trivia->ID,'question',true);\n\n $c = 0;\n $id = uniqid();\n if ( count( $question ) > 0 ) {\n if(is_array($question)){\n\n foreach( $question as $questions ) {\n if ( isset( $questions['question'] ) ) {\n\n\n printf('<p>Question: <input type=\"text\" name=\"question[%1$s][question]\" value=\"%2$s\"> -- <span class=\"remove_question\">%3$s</span><span class=\"add_answer\"> Add Answer</span></p>', $c,$questions['question'],__('Remove Question'));\n for($i = 1; $i<=count($questions['answers']); $i++)\n {\n if($questions['answers'][$i]['image'])\n {\n printf('<p>Option %5$s <input type=\"text\" value=\"%1$s\" name=\"question[%4$s][answers][%5$s][answer]\"> Status <input type=\"text\" value=\"%2$s\" name=\"question[%4$s][answers][%5$s][status]\"> Image <input type=\"text\" name=\"question[%4$s][answers][%5$s][image]\" value=\"%6$s\"><img src=\"%6$s\" height=\"100\" widht=\"100\"> -- <span class=\"remove_answer\">%3$s</span></p>', $questions['answers'][$i]['answer'] ,$questions['answers'][$i]['status'], __('Remove Answer'), $c, $i,$questions['answers'][$i]['image']);\n }\n else\n {\n printf('<p>Option %5$s <input type=\"text\" value=\"%1$s\" name=\"question[%4$s][answers][%5$s][answer]\"> Status <input type=\"text\" value=\"%2$s\" name=\"question[%4$s][answers][%5$s][status]\"> -- <span class=\"remove_answer\">%3$s</span></p>', $questions['answers'][$i]['answer'] ,$questions['answers'][$i]['status'], __('Remove Answer'), $c, $i);\n }\n }\n $c = $c +1;\n }\n }\n }\n}\n ?>\n<span id=\"question_here\"></span>\n<span class=\"add_question\"><?php _e('Add Question'); ?></span>\n<script>\n var $ =jQuery.noConflict();\n $(document).ready(function() {\n var count = <?php echo $c; ?>;\n var countt = 0;\n $(\".add_question\").click(function() {\n count = count + 1;\n countt = 0;\n $('#question_here').append('<p>Question: <input type=\"text\" name=\"question['+count+'][question]\" value=\"\"> -- <span class=\"remove_question\">Remove question</span><span class=\"add_answer\"> Add Answer</span></p>' );\n return false;\n });\n $(\".remove_question\").live('click', function() {\n $(this).parent().remove();\n });\n\n\n $(\".add_answer\").live('click',function(){\n countt = countt + 1;\n $('#question_here').append('<p>Answer <input type=\"text\" name=\"question['+count+'][answers]['+countt+'][answer]\"> Status <input type=\"text\" name=\"question['+count+'][answers]['+countt+'][status]\"><input id=\"question_'+count+'_answers_'+countt+'_image\" type=\"text\" size=\"36\" name=\"question['+count+'][answers]['+countt+'][image]\" value=\"\" /><input class=\"upload_image_button\" type=\"button\" value=\"Upload Image\" /><span class=\"remove_answer\">Remove</span></p>');\n })\n $('.upload_image_button').live('click',function() {\n formfield = $('#upload_image').attr('name');\n tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');\n\n return false;\n });\n\n window.send_to_editor = function(html) {\n imgurl = $('img',html).attr('src');\n $('#question_'+count+'_answers_'+countt+'_image').val(imgurl);\n tb_remove();\n }\n $(\".remove_answer\").live('click', function() {\n $(this).parent().remove();\n });\n\n });\n </script>\n</div><?php\n</code></pre>\n"
},
{
"answer_id": 201691,
"author": "Maikal",
"author_id": 38034,
"author_profile": "https://wordpress.stackexchange.com/users/38034",
"pm_score": 4,
"selected": true,
"text": "<p>here's my example of how to upload multiple images:</p>\n\n<pre><code>add_action( 'add_meta_boxes', 'my_test_metabox' );\n\nfunction my_test_metabox() {\n add_meta_box( 'my_test_metabox', 'File upload', 'my_test_metabox_out', 'post' );\n}\n\nadd_action('post_edit_form_tag', 'update_edit_form' );\nfunction update_edit_form() {\n echo ' enctype=\"multipart/form-data\"';\n}\n\nfunction my_test_metabox_out( $post ) {\n\n $files = get_post_meta( $post->ID, 'my_files', true );\n if( ! empty( $files ) ) {\n echo 'Files uploaded:' . \"\\r\\n\";\n foreach( $files as $file ) {\n echo '<img src=\"' . $file['url'] . '\" width=\"100\" height=\"100\" />';\n }\n echo \"\\r\\n\";\n }\n echo 'Upload files:' . \"\\r\\n\";\n echo '<input type=\"file\" name=\"my_files[]\" multiple />';\n\n}\n\nadd_action( 'save_post', 'my_files_save' );\n\nfunction my_files_save( $post_id ) {\n\n if( ! isset( $_FILES ) || empty( $_FILES ) || ! isset( $_FILES['my_files'] ) )\n return;\n\n if ( ! function_exists( 'wp_handle_upload' ) ) {\n require_once( ABSPATH . 'wp-admin/includes/file.php' );\n }\n $upload_overrides = array( 'test_form' => false );\n\n $files = $_FILES['my_files'];\n foreach ($files['name'] as $key => $value) {\n if ($files['name'][$key]) {\n $uploadedfile = array(\n 'name' => $files['name'][$key],\n 'type' => $files['type'][$key],\n 'tmp_name' => $files['tmp_name'][$key],\n 'error' => $files['error'][$key],\n 'size' => $files['size'][$key]\n );\n $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );\n\n if ( $movefile && !isset( $movefile['error'] ) ) {\n $ufiles = get_post_meta( $post_id, 'my_files', true );\n if( empty( $ufiles ) ) $ufiles = array();\n $ufiles[] = $movefile;\n update_post_meta( $post_id, 'my_files', $ufiles );\n\n }\n }\n }\n\n}\n</code></pre>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201676",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79858/"
] |
hi i am new on WordPress can somebody tell me how can i upload multiple images using wp\_handle\_upload in a loop
```
for($i=1;$i<count($_FILES['myfile']['name']);$i++){
$uploadedfile = $_FILES['myfile'].$i;
$upload_overrides = array( 'test_form'.$i => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) ) {
// echo "File is valid, and was successfully uploaded.\n";
$dir_path= $movefile['url'];
} else {
echo $movefile['error'];
}
}//end loop
```
|
here's my example of how to upload multiple images:
```
add_action( 'add_meta_boxes', 'my_test_metabox' );
function my_test_metabox() {
add_meta_box( 'my_test_metabox', 'File upload', 'my_test_metabox_out', 'post' );
}
add_action('post_edit_form_tag', 'update_edit_form' );
function update_edit_form() {
echo ' enctype="multipart/form-data"';
}
function my_test_metabox_out( $post ) {
$files = get_post_meta( $post->ID, 'my_files', true );
if( ! empty( $files ) ) {
echo 'Files uploaded:' . "\r\n";
foreach( $files as $file ) {
echo '<img src="' . $file['url'] . '" width="100" height="100" />';
}
echo "\r\n";
}
echo 'Upload files:' . "\r\n";
echo '<input type="file" name="my_files[]" multiple />';
}
add_action( 'save_post', 'my_files_save' );
function my_files_save( $post_id ) {
if( ! isset( $_FILES ) || empty( $_FILES ) || ! isset( $_FILES['my_files'] ) )
return;
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$upload_overrides = array( 'test_form' => false );
$files = $_FILES['my_files'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$uploadedfile = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) ) {
$ufiles = get_post_meta( $post_id, 'my_files', true );
if( empty( $ufiles ) ) $ufiles = array();
$ufiles[] = $movefile;
update_post_meta( $post_id, 'my_files', $ufiles );
}
}
}
}
```
|
201,684 |
<p>I am using <a href="http://metabox.io" rel="nofollow">metabox's</a> advance file uploader to upload images.</p>
<pre><code><?php $images = rwmb_meta( 'tj_file_advanced', 'type=image&size=YOURSIZE');
foreach ( $images as $image ) { ?>
<div class="col-md-4">
<div class="boxe">
<?php echo "<img src='{$image['full_url']}'/>"; ?>
</div>
</div>
<?php } ?>
<div class="loadmore" onclick="loadMore()"></div>
</code></pre>
<p>Currently, I have only uploaded 3 images, so it only shows 3 images. I want to upload more images. It should only show 3 images in the beginning and after i click the load more it should show another 3 images and show on. </p>
|
[
{
"answer_id": 201687,
"author": "Maikal",
"author_id": 38034,
"author_profile": "https://wordpress.stackexchange.com/users/38034",
"pm_score": 0,
"selected": false,
"text": "<p>ok. so your <code>loadMore()</code> should do something like these:</p>\n\n<pre><code>function loadMore() {\n var showing = $('#id').find( '> .col-md-4').length;\n $.ajax(\n // making ajax call to get more images passing variable showing\n success: function( data ) {\n $('#id').append( data );\n }\n );\n}\n</code></pre>\n\n<p>and your php (ajax) script should return something like:</p>\n\n<pre><code>$images = rwmb_meta( 'tj_file_advanced', 'type=image&size=YOURSIZE');\n$count = count( $images );\n$offset = (int) $_POST['showing'];\nfor( $i = $offset; $i <= $count; $i++ ) {\n echo '<div class=\"col-md-4\">\n <div class=\"boxe\">\n <img src=\"' . $images[$i]['full_url']. '\" />\n </div>\n </div>';\n}\ndie();\n</code></pre>\n\n<p>Note that you should wrap all your <code>col-md-4</code> in <code>#id</code></p>\n"
},
{
"answer_id": 239024,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 1,
"selected": false,
"text": "<p>It can be done just following regular way to use Ajax in WordPress. </p>\n\n<p><a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n\n<p>First register a script file and also create an AJAX Call.</p>\n\n<pre><code>wp_enqueue_script( 'meta-ajaxscript', get_stylesheet_directory_uri() . '/js/ajax-init.js', array( 'jquery' ), '', true );\nwp_localize_script( 'meta-ajaxscript', 'ajaxMeta', array(\n 'ajaxurl' => admin_url( 'admin-ajax.php' )\n));\n</code></pre>\n\n<p>Second, Wrap your metadata with a parent element by class or ID</p>\n\n<pre><code><div id=\"metaWrapper\">\n\n <?php \n $images = rwmb_meta( 'tj_file_advanced', 'type=image&size=YOURSIZE'); \n $ppp = 3;\n foreach (array_slice($images, 0, $ppp) as $image) { ?>\n <div class=\"col-md-4\">\n <div class=\"boxe\">\n <?php echo \"<img src='{$image['full_url']}'/>\"; ?>\n </div>\n </div>\n <?php } ?>\n\n</div>\n\n<div class=\"loadmore\"></div>\n</code></pre>\n\n<p>Third write down some ajax call script into ajax-init.js.</p>\n\n<pre><code>$( \".loadmore\" ).on( \"click\", function(e) {\n e.preventDefault();\n\n var $container = $('#metaWrapper'),\n ppp = 3,\n number = $container.find( '> .col-md-4').length,\n page = number / ppp;\n\n $.ajax({\n url: ajaxMeta.ajaxurl,\n type: 'post',\n data: {\n 'page': page,\n 'ppp': ppp,\n action: 'meta_fetch'\n },\n success: function( response ) {\n if(response == \"\")\n {\n // no content was found\n $('.loadmore').hide();\n }\n else\n {\n console.log(response);\n $container.append( response );\n }\n }\n });\n\n return false;\n});\n</code></pre>\n\n<p>Now set up a PHP function to handle the AJAX request. </p>\n\n<pre><code>add_action( 'wp_ajax_nopriv_meta_fetch', 'wpex_metadata_fetch' );\nadd_action( 'wp_ajax_meta_fetch', 'wpex_metadata_fetch' );\n\nfunction wpex_metadata_fetch() {\n\n $images = rwmb_meta( 'tj_file_advanced', 'type=image&size=YOURSIZE');\n\n $page = (int) $_POST['page'];\n $ppp = (int) $_POST['ppp'];\n\n foreach (array_slice($images, $page*$ppp, $ppp) as $image) { ?>\n <div class=\"col-md-4\">\n <div class=\"boxe\">\n <?php echo \"<img src='{$image['full_url']}'/>\"; ?>\n </div>\n </div>\n <?php\n } \n\n die();\n\n}\n</code></pre>\n\n<p>hope it makes sense and happy Codding!</p>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201684",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75729/"
] |
I am using [metabox's](http://metabox.io) advance file uploader to upload images.
```
<?php $images = rwmb_meta( 'tj_file_advanced', 'type=image&size=YOURSIZE');
foreach ( $images as $image ) { ?>
<div class="col-md-4">
<div class="boxe">
<?php echo "<img src='{$image['full_url']}'/>"; ?>
</div>
</div>
<?php } ?>
<div class="loadmore" onclick="loadMore()"></div>
```
Currently, I have only uploaded 3 images, so it only shows 3 images. I want to upload more images. It should only show 3 images in the beginning and after i click the load more it should show another 3 images and show on.
|
It can be done just following regular way to use Ajax in WordPress.
<https://codex.wordpress.org/AJAX_in_Plugins>
First register a script file and also create an AJAX Call.
```
wp_enqueue_script( 'meta-ajaxscript', get_stylesheet_directory_uri() . '/js/ajax-init.js', array( 'jquery' ), '', true );
wp_localize_script( 'meta-ajaxscript', 'ajaxMeta', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
```
Second, Wrap your metadata with a parent element by class or ID
```
<div id="metaWrapper">
<?php
$images = rwmb_meta( 'tj_file_advanced', 'type=image&size=YOURSIZE');
$ppp = 3;
foreach (array_slice($images, 0, $ppp) as $image) { ?>
<div class="col-md-4">
<div class="boxe">
<?php echo "<img src='{$image['full_url']}'/>"; ?>
</div>
</div>
<?php } ?>
</div>
<div class="loadmore"></div>
```
Third write down some ajax call script into ajax-init.js.
```
$( ".loadmore" ).on( "click", function(e) {
e.preventDefault();
var $container = $('#metaWrapper'),
ppp = 3,
number = $container.find( '> .col-md-4').length,
page = number / ppp;
$.ajax({
url: ajaxMeta.ajaxurl,
type: 'post',
data: {
'page': page,
'ppp': ppp,
action: 'meta_fetch'
},
success: function( response ) {
if(response == "")
{
// no content was found
$('.loadmore').hide();
}
else
{
console.log(response);
$container.append( response );
}
}
});
return false;
});
```
Now set up a PHP function to handle the AJAX request.
```
add_action( 'wp_ajax_nopriv_meta_fetch', 'wpex_metadata_fetch' );
add_action( 'wp_ajax_meta_fetch', 'wpex_metadata_fetch' );
function wpex_metadata_fetch() {
$images = rwmb_meta( 'tj_file_advanced', 'type=image&size=YOURSIZE');
$page = (int) $_POST['page'];
$ppp = (int) $_POST['ppp'];
foreach (array_slice($images, $page*$ppp, $ppp) as $image) { ?>
<div class="col-md-4">
<div class="boxe">
<?php echo "<img src='{$image['full_url']}'/>"; ?>
</div>
</div>
<?php
}
die();
}
```
hope it makes sense and happy Codding!
|
201,699 |
<p>I recently noticed after performance errors and failure that the memory that a single request was consuming (either front or back) was increased rapidly. After hours of experiments and research I noticed that the option_value record of the "cron" row was 7MB!!!! containing a huge json with a loop of "reschedule" action.</p>
<p>It seems something like an attack and prepare to see it again? How I can protect my site from these cron values?</p>
|
[
{
"answer_id": 201740,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 0,
"selected": false,
"text": "<p>You might be suffering from a bug introduced with WordPress 4.3, involving term splitting.</p>\n\n<p>There's a hotfix plugin available here: <a href=\"https://wordpress.org/plugins/wp33423-hotfix/\" rel=\"nofollow\">https://wordpress.org/plugins/wp33423-hotfix/</a></p>\n"
},
{
"answer_id": 327420,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": -1,
"selected": false,
"text": "<p>why don't you disable <strong>wp-cron.php</strong> file? Simply paste this code in your <strong>wp-config.php</strong> file and no scheduled task works after you disable the cron file.</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n"
},
{
"answer_id": 396042,
"author": "kovshenin",
"author_id": 1316,
"author_profile": "https://wordpress.stackexchange.com/users/1316",
"pm_score": 1,
"selected": false,
"text": "<p>This could be caused by many different things, as well as a result of a broken cron setup, where actions are being scheduled, but never run.</p>\n<p>The best way forward is to try and understand what is actually being scheduled or rescheduled, what are the action names? If you can find the action names, you'll be able to pinpoint it to a specific plugin or theme (or core for that matter).</p>\n<p>If you have WP-CLI available to you, you could run:</p>\n<pre><code>wp cron event list\n</code></pre>\n<p>Though with 7mb of cron data, that can take a while, so be patient. When you figure out the action name, you can delete them all with:</p>\n<pre><code>wp cron event delete <action_name>\n</code></pre>\n<p>If you don't have WP-CLI access, you can try to inspect the option value directly in the database (via phpMyAdmin or MySQL CLI), or in your database export .sql file.</p>\n<p>I do not recommend disabling the WordPress cron as somebody else suggested here, as this will not prevent new actions from being queued, and will also break cron-dependant functionality across the entire site, including things like scheduled posts, update checks, etc.</p>\n<p>Hope that helps.</p>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201699",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78616/"
] |
I recently noticed after performance errors and failure that the memory that a single request was consuming (either front or back) was increased rapidly. After hours of experiments and research I noticed that the option\_value record of the "cron" row was 7MB!!!! containing a huge json with a loop of "reschedule" action.
It seems something like an attack and prepare to see it again? How I can protect my site from these cron values?
|
This could be caused by many different things, as well as a result of a broken cron setup, where actions are being scheduled, but never run.
The best way forward is to try and understand what is actually being scheduled or rescheduled, what are the action names? If you can find the action names, you'll be able to pinpoint it to a specific plugin or theme (or core for that matter).
If you have WP-CLI available to you, you could run:
```
wp cron event list
```
Though with 7mb of cron data, that can take a while, so be patient. When you figure out the action name, you can delete them all with:
```
wp cron event delete <action_name>
```
If you don't have WP-CLI access, you can try to inspect the option value directly in the database (via phpMyAdmin or MySQL CLI), or in your database export .sql file.
I do not recommend disabling the WordPress cron as somebody else suggested here, as this will not prevent new actions from being queued, and will also break cron-dependant functionality across the entire site, including things like scheduled posts, update checks, etc.
Hope that helps.
|
201,709 |
<p><strong>EDIT : I answered myself.</strong></p>
<p>Simple request for you. I am trying to develop a code that search for post for TODAY. If it returns nothing, then get the latest post before today.</p>
<p>For now, I have made a small algorithm to expose your my question.</p>
<pre><code><?php
// WP_Query arguments
$args = array (
'post_type' => array( 'post' ),
'year' => date('Y'),
'monthnum' => date('m'),
'day' => date('d'),
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
}
} else {
// no posts found (Here I need to make the new request)
$args_before = array (
'post_type' => array( 'post' ),
'year' => date('Y'),
'monthnum' => date('m'),
'day' => date('d'),
);
// Classic query will go here ...
}
// Restore original Post Data
wp_reset_postdata();
?>
</code></pre>
<p>I start with my first array($args) that search for post for TODAY and then I check if I have results.</p>
<p>The tricky part, if I have no posts, do I need to work in the else{} and how can I acheive to get the previous first post before TODAY?</p>
<p>Do I need to work with <code>BETWEEN</code> and <code>ORDER DESC</code> ? </p>
<p>Any clue?</p>
|
[
{
"answer_id": 201740,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 0,
"selected": false,
"text": "<p>You might be suffering from a bug introduced with WordPress 4.3, involving term splitting.</p>\n\n<p>There's a hotfix plugin available here: <a href=\"https://wordpress.org/plugins/wp33423-hotfix/\" rel=\"nofollow\">https://wordpress.org/plugins/wp33423-hotfix/</a></p>\n"
},
{
"answer_id": 327420,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": -1,
"selected": false,
"text": "<p>why don't you disable <strong>wp-cron.php</strong> file? Simply paste this code in your <strong>wp-config.php</strong> file and no scheduled task works after you disable the cron file.</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n"
},
{
"answer_id": 396042,
"author": "kovshenin",
"author_id": 1316,
"author_profile": "https://wordpress.stackexchange.com/users/1316",
"pm_score": 1,
"selected": false,
"text": "<p>This could be caused by many different things, as well as a result of a broken cron setup, where actions are being scheduled, but never run.</p>\n<p>The best way forward is to try and understand what is actually being scheduled or rescheduled, what are the action names? If you can find the action names, you'll be able to pinpoint it to a specific plugin or theme (or core for that matter).</p>\n<p>If you have WP-CLI available to you, you could run:</p>\n<pre><code>wp cron event list\n</code></pre>\n<p>Though with 7mb of cron data, that can take a while, so be patient. When you figure out the action name, you can delete them all with:</p>\n<pre><code>wp cron event delete <action_name>\n</code></pre>\n<p>If you don't have WP-CLI access, you can try to inspect the option value directly in the database (via phpMyAdmin or MySQL CLI), or in your database export .sql file.</p>\n<p>I do not recommend disabling the WordPress cron as somebody else suggested here, as this will not prevent new actions from being queued, and will also break cron-dependant functionality across the entire site, including things like scheduled posts, update checks, etc.</p>\n<p>Hope that helps.</p>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32365/"
] |
**EDIT : I answered myself.**
Simple request for you. I am trying to develop a code that search for post for TODAY. If it returns nothing, then get the latest post before today.
For now, I have made a small algorithm to expose your my question.
```
<?php
// WP_Query arguments
$args = array (
'post_type' => array( 'post' ),
'year' => date('Y'),
'monthnum' => date('m'),
'day' => date('d'),
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
}
} else {
// no posts found (Here I need to make the new request)
$args_before = array (
'post_type' => array( 'post' ),
'year' => date('Y'),
'monthnum' => date('m'),
'day' => date('d'),
);
// Classic query will go here ...
}
// Restore original Post Data
wp_reset_postdata();
?>
```
I start with my first array($args) that search for post for TODAY and then I check if I have results.
The tricky part, if I have no posts, do I need to work in the else{} and how can I acheive to get the previous first post before TODAY?
Do I need to work with `BETWEEN` and `ORDER DESC` ?
Any clue?
|
This could be caused by many different things, as well as a result of a broken cron setup, where actions are being scheduled, but never run.
The best way forward is to try and understand what is actually being scheduled or rescheduled, what are the action names? If you can find the action names, you'll be able to pinpoint it to a specific plugin or theme (or core for that matter).
If you have WP-CLI available to you, you could run:
```
wp cron event list
```
Though with 7mb of cron data, that can take a while, so be patient. When you figure out the action name, you can delete them all with:
```
wp cron event delete <action_name>
```
If you don't have WP-CLI access, you can try to inspect the option value directly in the database (via phpMyAdmin or MySQL CLI), or in your database export .sql file.
I do not recommend disabling the WordPress cron as somebody else suggested here, as this will not prevent new actions from being queued, and will also break cron-dependant functionality across the entire site, including things like scheduled posts, update checks, etc.
Hope that helps.
|
201,715 |
<p>I've made a woocommerce store and I am using a dropshipper - so every product has an price and a trade price for me - which I am importing and storing as a custom field 'trade_price' on the product.</p>
<p>I wanted to know if it would be possible to include some php on my single product template which would show me 1) profit per item (price minus trade price) and 2) margin on said product (percentage difference between trade price and sale price)</p>
|
[
{
"answer_id": 201740,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 0,
"selected": false,
"text": "<p>You might be suffering from a bug introduced with WordPress 4.3, involving term splitting.</p>\n\n<p>There's a hotfix plugin available here: <a href=\"https://wordpress.org/plugins/wp33423-hotfix/\" rel=\"nofollow\">https://wordpress.org/plugins/wp33423-hotfix/</a></p>\n"
},
{
"answer_id": 327420,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": -1,
"selected": false,
"text": "<p>why don't you disable <strong>wp-cron.php</strong> file? Simply paste this code in your <strong>wp-config.php</strong> file and no scheduled task works after you disable the cron file.</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n"
},
{
"answer_id": 396042,
"author": "kovshenin",
"author_id": 1316,
"author_profile": "https://wordpress.stackexchange.com/users/1316",
"pm_score": 1,
"selected": false,
"text": "<p>This could be caused by many different things, as well as a result of a broken cron setup, where actions are being scheduled, but never run.</p>\n<p>The best way forward is to try and understand what is actually being scheduled or rescheduled, what are the action names? If you can find the action names, you'll be able to pinpoint it to a specific plugin or theme (or core for that matter).</p>\n<p>If you have WP-CLI available to you, you could run:</p>\n<pre><code>wp cron event list\n</code></pre>\n<p>Though with 7mb of cron data, that can take a while, so be patient. When you figure out the action name, you can delete them all with:</p>\n<pre><code>wp cron event delete <action_name>\n</code></pre>\n<p>If you don't have WP-CLI access, you can try to inspect the option value directly in the database (via phpMyAdmin or MySQL CLI), or in your database export .sql file.</p>\n<p>I do not recommend disabling the WordPress cron as somebody else suggested here, as this will not prevent new actions from being queued, and will also break cron-dependant functionality across the entire site, including things like scheduled posts, update checks, etc.</p>\n<p>Hope that helps.</p>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201715",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51830/"
] |
I've made a woocommerce store and I am using a dropshipper - so every product has an price and a trade price for me - which I am importing and storing as a custom field 'trade\_price' on the product.
I wanted to know if it would be possible to include some php on my single product template which would show me 1) profit per item (price minus trade price) and 2) margin on said product (percentage difference between trade price and sale price)
|
This could be caused by many different things, as well as a result of a broken cron setup, where actions are being scheduled, but never run.
The best way forward is to try and understand what is actually being scheduled or rescheduled, what are the action names? If you can find the action names, you'll be able to pinpoint it to a specific plugin or theme (or core for that matter).
If you have WP-CLI available to you, you could run:
```
wp cron event list
```
Though with 7mb of cron data, that can take a while, so be patient. When you figure out the action name, you can delete them all with:
```
wp cron event delete <action_name>
```
If you don't have WP-CLI access, you can try to inspect the option value directly in the database (via phpMyAdmin or MySQL CLI), or in your database export .sql file.
I do not recommend disabling the WordPress cron as somebody else suggested here, as this will not prevent new actions from being queued, and will also break cron-dependant functionality across the entire site, including things like scheduled posts, update checks, etc.
Hope that helps.
|
201,722 |
<p>Is there a way to count and show the count of all author posts in a custom post type except the current logged in user? </p>
<p>I was hoping there's a way to do it with <code>count_many_users_posts</code> but it doesn't appear there is a way to exclude authors, only include them.</p>
<p>I've done multiple searches but have found nothing to even hint at a right direction to head in.</p>
<p>Here's the codex example:</p>
<pre><code><?php
$users = array(1, 3, 9, 10);
$counts = count_many_users_posts($users);
echo 'Posts made by user 3: ' . $counts[3];
?>
</code></pre>
<p>TIA!</p>
<p>ON EDIT:</p>
<p>Just wanted to let y'all know I haven't revisited this yet. I will try the solutions and come back when I get there. Another project popped up for the moment. </p>
<p>Thanks!</p>
|
[
{
"answer_id": 201724,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>Inclusion and exclusion are often reversible. \"Not this\" (exclusive) is equal to \"All of that, skipping this\" (inclusive).</p>\n\n<p>If in general the function does precisely what you need, you could just make a full list of user IDs and throwing the current one out.</p>\n"
},
{
"answer_id": 201725,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>If the number of users on your site, is relatively small, you could try:</p>\n\n<pre><code>$user_ids = get_users( \n [ \n 'fields' => 'ID', // Only return the user IDs\n 'exclude' => (array) get_current_user_id(), // Exclude the current user\n 'number' => 10 // Modify this number to your needs\n ] \n);\n</code></pre>\n\n<p>and then use this as an input into the <code>count_many_users_posts()</code> function:</p>\n\n<pre><code>$counts = count_many_users_posts( \n (array) $user_ids,\n $post_type = 'post', \n $public_only = false \n);\n</code></pre>\n\n<p>where you can adjust the post type to your needs.</p>\n"
},
{
"answer_id": 201730,
"author": "Dustin Woods",
"author_id": 79899,
"author_profile": "https://wordpress.stackexchange.com/users/79899",
"pm_score": 1,
"selected": false,
"text": "<p>There are a number of WordPress query functions you could utilize, but I recommend keeping the query lean and avoid using a WP_Query since you don't need the post content. Here's a little function that will return the number of posts of post_type that are not owned by user_id:</p>\n\n<pre><code>function get_post_count_exclude_user($post_type,$user_id) {\n $query = \"SELECT COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s AND post_author <> %s\";\n return $wpdb->get_var( $wpdb->prepare( $query, $post_type, $user_id ) );\n}\n\n$number_of_posts = get_post_count_exclude_user('my_post_type',get_current_user_id());\n</code></pre>\n"
},
{
"answer_id": 202320,
"author": "Justice Is Cheap",
"author_id": 7662,
"author_profile": "https://wordpress.stackexchange.com/users/7662",
"pm_score": 1,
"selected": true,
"text": "<p>I don't know why this works, but it does.</p>\n\n<pre><code> $authorid = get_current_user_id();\n query_posts(array( \n 'post_type' => 'tasks',\n 'author' => -$authorid,\n ) ); \n $count = 0;\n while (have_posts()) : the_post(); \n $count++; \n endwhile;\n echo '<p class=\"else\"><em>' .$count .'</em></p><span class=\"description\">All other posts</span>';\n wp_reset_query();\n</code></pre>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201722",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7662/"
] |
Is there a way to count and show the count of all author posts in a custom post type except the current logged in user?
I was hoping there's a way to do it with `count_many_users_posts` but it doesn't appear there is a way to exclude authors, only include them.
I've done multiple searches but have found nothing to even hint at a right direction to head in.
Here's the codex example:
```
<?php
$users = array(1, 3, 9, 10);
$counts = count_many_users_posts($users);
echo 'Posts made by user 3: ' . $counts[3];
?>
```
TIA!
ON EDIT:
Just wanted to let y'all know I haven't revisited this yet. I will try the solutions and come back when I get there. Another project popped up for the moment.
Thanks!
|
I don't know why this works, but it does.
```
$authorid = get_current_user_id();
query_posts(array(
'post_type' => 'tasks',
'author' => -$authorid,
) );
$count = 0;
while (have_posts()) : the_post();
$count++;
endwhile;
echo '<p class="else"><em>' .$count .'</em></p><span class="description">All other posts</span>';
wp_reset_query();
```
|
201,728 |
<p>We are experiencing very slow performance with queries that use <code>SQL_CALC_FOUND_ROWS</code> within the admin section of WordPress.</p>
<p>We currently have about 125,000 posts on our site and use Varnish to cache the front-end and are on WordPress version 4.2.3.</p>
<p>The problem arises when there are people using the admin section of WordPress and WordPress will run a query like the one below:</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1 AND (((wp_posts.post_title LIKE '%denali%')
OR (wp_posts.post_content LIKE '%denali%')))
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish'
OR wp_posts.post_status = 'future'
OR wp_posts.post_status = 'draft'
OR wp_posts.post_status = 'pending'
OR wp_posts.post_status = 'private')
ORDER BY wp_posts.post_title LIKE '%denali%' DESC,
wp_posts.post_date DESC LIMIT 0, 20
</code></pre>
<p>Is there a patch to fix this issue or some sort of <code>pre_get_posts</code> filter I can run?</p>
<p>I plan on removing some post revisions and doing some DB optimization, but first wanted to see if there was some sort of fix for this within WordPress.</p>
<p>I have come across similar issues while searching for this, but most of those issues seem to be 2-6 years old.</p>
|
[
{
"answer_id": 257665,
"author": "Younes Nesta",
"author_id": 114028,
"author_profile": "https://wordpress.stackexchange.com/users/114028",
"pm_score": -1,
"selected": false,
"text": "<p>$query->set('no_found_rows', true);</p>\n"
},
{
"answer_id": 271031,
"author": "Anastis",
"author_id": 75475,
"author_profile": "https://wordpress.stackexchange.com/users/75475",
"pm_score": 1,
"selected": false,
"text": "<p>The use of <code>SQL_CALC_FOUND_ROWS</code> is not really a problem, although it incurs an overhead.</p>\n\n<p>What happens is, WordPress uses <code>SQL_CALC_FOUND_ROWS</code> in order to determine the total posts that would have been returned, if no <code>LIMIT</code> clause was provided. This is necessary in order to calculate and provide you with correct pagination links.</p>\n\n<p>Disabling it unconditionally is guaranteed to break things all over the place.</p>\n\n<p>If you can identify specific queries that suffer from its use, and you can do without pagination, then you could hook to <code>pre_get_posts</code> and conditionally set the <code>no_found_rows</code> parameter to true.\nThis, however, is more a hack than a solution.</p>\n\n<p>The proper solution is to use a database query caching mechanism, either on the side of the database, or on the WordPress side using a plugin such as <a href=\"https://github.com/Automattic/advanced-post-cache\" rel=\"nofollow noreferrer\">Advanced Post Cache</a> (developed for and used in WordPress.com)</p>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201728",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57849/"
] |
We are experiencing very slow performance with queries that use `SQL_CALC_FOUND_ROWS` within the admin section of WordPress.
We currently have about 125,000 posts on our site and use Varnish to cache the front-end and are on WordPress version 4.2.3.
The problem arises when there are people using the admin section of WordPress and WordPress will run a query like the one below:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1 AND (((wp_posts.post_title LIKE '%denali%')
OR (wp_posts.post_content LIKE '%denali%')))
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish'
OR wp_posts.post_status = 'future'
OR wp_posts.post_status = 'draft'
OR wp_posts.post_status = 'pending'
OR wp_posts.post_status = 'private')
ORDER BY wp_posts.post_title LIKE '%denali%' DESC,
wp_posts.post_date DESC LIMIT 0, 20
```
Is there a patch to fix this issue or some sort of `pre_get_posts` filter I can run?
I plan on removing some post revisions and doing some DB optimization, but first wanted to see if there was some sort of fix for this within WordPress.
I have come across similar issues while searching for this, but most of those issues seem to be 2-6 years old.
|
The use of `SQL_CALC_FOUND_ROWS` is not really a problem, although it incurs an overhead.
What happens is, WordPress uses `SQL_CALC_FOUND_ROWS` in order to determine the total posts that would have been returned, if no `LIMIT` clause was provided. This is necessary in order to calculate and provide you with correct pagination links.
Disabling it unconditionally is guaranteed to break things all over the place.
If you can identify specific queries that suffer from its use, and you can do without pagination, then you could hook to `pre_get_posts` and conditionally set the `no_found_rows` parameter to true.
This, however, is more a hack than a solution.
The proper solution is to use a database query caching mechanism, either on the side of the database, or on the WordPress side using a plugin such as [Advanced Post Cache](https://github.com/Automattic/advanced-post-cache) (developed for and used in WordPress.com)
|
201,729 |
<p>I added an extra registration field:</p>
<pre><code>function wooc_extra_register_fields() {
?><p class="form-row form-row-first">
<label for="billing_cpf"><?php _e( 'CPF', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_cpf" id="billing_cpf" value="<?php
if ( ! empty( $_POST['billing_cpf'] ) ) esc_attr_e( $_POST['billing_cpf'] ); ?>" />
</p><?php
}
add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );
function wooc_save_extra_register_fields( $customer_id ) {
if ( isset( $_POST['billing_cpf'] ) ) {
update_user_meta( $customer_id, 'billing_cpf', sanitize_text_field( $_POST['billing_cpf'] ) );
}
}
add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );
</code></pre>
<p>I added a mask and some functions to validate the information. This information is saved and shown on the WordPress dashboard with this code:</p>
<pre><code>function theme_add_user_cpf_column( $columns ) {
$columns['billing_cpf'] = __( 'CPF', 'theme' );
return $columns;
}
add_filter( 'manage_users_columns', 'theme_add_user_cpf_column' );
function theme_show_user_cpf_data( $value, $column_name, $user_id ) {
if( 'billing_cpf' == $column_name ) {
return get_user_meta( $user_id, 'billing_cpf', true );
}
}
add_action( 'manage_users_custom_column', 'theme_show_user_cpf_data', 10, 3 );
</code></pre>
<p>Everything works fine, but I need to check if meta <code>billing_cpf</code> already exists before saving (unique information per user). How can I do that?</p>
|
[
{
"answer_id": 257665,
"author": "Younes Nesta",
"author_id": 114028,
"author_profile": "https://wordpress.stackexchange.com/users/114028",
"pm_score": -1,
"selected": false,
"text": "<p>$query->set('no_found_rows', true);</p>\n"
},
{
"answer_id": 271031,
"author": "Anastis",
"author_id": 75475,
"author_profile": "https://wordpress.stackexchange.com/users/75475",
"pm_score": 1,
"selected": false,
"text": "<p>The use of <code>SQL_CALC_FOUND_ROWS</code> is not really a problem, although it incurs an overhead.</p>\n\n<p>What happens is, WordPress uses <code>SQL_CALC_FOUND_ROWS</code> in order to determine the total posts that would have been returned, if no <code>LIMIT</code> clause was provided. This is necessary in order to calculate and provide you with correct pagination links.</p>\n\n<p>Disabling it unconditionally is guaranteed to break things all over the place.</p>\n\n<p>If you can identify specific queries that suffer from its use, and you can do without pagination, then you could hook to <code>pre_get_posts</code> and conditionally set the <code>no_found_rows</code> parameter to true.\nThis, however, is more a hack than a solution.</p>\n\n<p>The proper solution is to use a database query caching mechanism, either on the side of the database, or on the WordPress side using a plugin such as <a href=\"https://github.com/Automattic/advanced-post-cache\" rel=\"nofollow noreferrer\">Advanced Post Cache</a> (developed for and used in WordPress.com)</p>\n"
}
] |
2015/09/04
|
[
"https://wordpress.stackexchange.com/questions/201729",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79900/"
] |
I added an extra registration field:
```
function wooc_extra_register_fields() {
?><p class="form-row form-row-first">
<label for="billing_cpf"><?php _e( 'CPF', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_cpf" id="billing_cpf" value="<?php
if ( ! empty( $_POST['billing_cpf'] ) ) esc_attr_e( $_POST['billing_cpf'] ); ?>" />
</p><?php
}
add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );
function wooc_save_extra_register_fields( $customer_id ) {
if ( isset( $_POST['billing_cpf'] ) ) {
update_user_meta( $customer_id, 'billing_cpf', sanitize_text_field( $_POST['billing_cpf'] ) );
}
}
add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );
```
I added a mask and some functions to validate the information. This information is saved and shown on the WordPress dashboard with this code:
```
function theme_add_user_cpf_column( $columns ) {
$columns['billing_cpf'] = __( 'CPF', 'theme' );
return $columns;
}
add_filter( 'manage_users_columns', 'theme_add_user_cpf_column' );
function theme_show_user_cpf_data( $value, $column_name, $user_id ) {
if( 'billing_cpf' == $column_name ) {
return get_user_meta( $user_id, 'billing_cpf', true );
}
}
add_action( 'manage_users_custom_column', 'theme_show_user_cpf_data', 10, 3 );
```
Everything works fine, but I need to check if meta `billing_cpf` already exists before saving (unique information per user). How can I do that?
|
The use of `SQL_CALC_FOUND_ROWS` is not really a problem, although it incurs an overhead.
What happens is, WordPress uses `SQL_CALC_FOUND_ROWS` in order to determine the total posts that would have been returned, if no `LIMIT` clause was provided. This is necessary in order to calculate and provide you with correct pagination links.
Disabling it unconditionally is guaranteed to break things all over the place.
If you can identify specific queries that suffer from its use, and you can do without pagination, then you could hook to `pre_get_posts` and conditionally set the `no_found_rows` parameter to true.
This, however, is more a hack than a solution.
The proper solution is to use a database query caching mechanism, either on the side of the database, or on the WordPress side using a plugin such as [Advanced Post Cache](https://github.com/Automattic/advanced-post-cache) (developed for and used in WordPress.com)
|
201,745 |
<p>I have wordpress installed on my root (<code>/var/www/html</code>) and I have a sub-directory in the root as <code>/var/www/html/manage</code> Both directories have it's own <code>.htaccess</code> files. Content of the <code>.htaccess</code> are as follows.</p>
<h2>/var/www/html/.htaccess (root)</h2>
<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>
<h2>/var/www/html/manage/.htaccess (Sub-directory)</h2>
<pre><code># Start Manage .htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
ErrorDocument 404 /lost.php
# End Manage .htaccess
</code></pre>
<p>I can rewrite <code>.php</code> extension of the the <code>php</code> files in the sub-directory with the .htaccess but I cannot use custom 404 as defined in the htaccess file in the sub-directory. When I go to <code>www.example.com/manage/laksjdflskjf</code> it shows wordpress 404 instead of <code>lost.php</code></p>
<p>How Can I make the sub-directory to show its 404 instead of wordpress 404?</p>
|
[
{
"answer_id": 257665,
"author": "Younes Nesta",
"author_id": 114028,
"author_profile": "https://wordpress.stackexchange.com/users/114028",
"pm_score": -1,
"selected": false,
"text": "<p>$query->set('no_found_rows', true);</p>\n"
},
{
"answer_id": 271031,
"author": "Anastis",
"author_id": 75475,
"author_profile": "https://wordpress.stackexchange.com/users/75475",
"pm_score": 1,
"selected": false,
"text": "<p>The use of <code>SQL_CALC_FOUND_ROWS</code> is not really a problem, although it incurs an overhead.</p>\n\n<p>What happens is, WordPress uses <code>SQL_CALC_FOUND_ROWS</code> in order to determine the total posts that would have been returned, if no <code>LIMIT</code> clause was provided. This is necessary in order to calculate and provide you with correct pagination links.</p>\n\n<p>Disabling it unconditionally is guaranteed to break things all over the place.</p>\n\n<p>If you can identify specific queries that suffer from its use, and you can do without pagination, then you could hook to <code>pre_get_posts</code> and conditionally set the <code>no_found_rows</code> parameter to true.\nThis, however, is more a hack than a solution.</p>\n\n<p>The proper solution is to use a database query caching mechanism, either on the side of the database, or on the WordPress side using a plugin such as <a href=\"https://github.com/Automattic/advanced-post-cache\" rel=\"nofollow noreferrer\">Advanced Post Cache</a> (developed for and used in WordPress.com)</p>\n"
}
] |
2015/09/05
|
[
"https://wordpress.stackexchange.com/questions/201745",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79907/"
] |
I have wordpress installed on my root (`/var/www/html`) and I have a sub-directory in the root as `/var/www/html/manage` Both directories have it's own `.htaccess` files. Content of the `.htaccess` are as follows.
/var/www/html/.htaccess (root)
------------------------------
```
# 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
```
/var/www/html/manage/.htaccess (Sub-directory)
----------------------------------------------
```
# Start Manage .htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
ErrorDocument 404 /lost.php
# End Manage .htaccess
```
I can rewrite `.php` extension of the the `php` files in the sub-directory with the .htaccess but I cannot use custom 404 as defined in the htaccess file in the sub-directory. When I go to `www.example.com/manage/laksjdflskjf` it shows wordpress 404 instead of `lost.php`
How Can I make the sub-directory to show its 404 instead of wordpress 404?
|
The use of `SQL_CALC_FOUND_ROWS` is not really a problem, although it incurs an overhead.
What happens is, WordPress uses `SQL_CALC_FOUND_ROWS` in order to determine the total posts that would have been returned, if no `LIMIT` clause was provided. This is necessary in order to calculate and provide you with correct pagination links.
Disabling it unconditionally is guaranteed to break things all over the place.
If you can identify specific queries that suffer from its use, and you can do without pagination, then you could hook to `pre_get_posts` and conditionally set the `no_found_rows` parameter to true.
This, however, is more a hack than a solution.
The proper solution is to use a database query caching mechanism, either on the side of the database, or on the WordPress side using a plugin such as [Advanced Post Cache](https://github.com/Automattic/advanced-post-cache) (developed for and used in WordPress.com)
|
201,756 |
<p>On the multisite main page (<a href="http://example.com/" rel="nofollow">http://example.com/</a>) I have a login-form where users can login to their multisite like so:</p>
<pre><code><?php
$args = array(
'redirect' => get_active_blog_for_user(),
);
wp_login_form( $args );
?>
</code></pre>
<p>After logging in they will be redirected to their dashboard (http:// example.com/userblog/wp-admin/). I don't want them to be redirected to their dashboard. I want them to be redirected to their mainpage instead (<a href="http://example.com/userblog/" rel="nofollow">http://example.com/userblog/</a>). How can I achieve this?</p>
<p>Kind regards
Johan</p>
|
[
{
"answer_id": 202493,
"author": "Johan Ndiyo Linnarsson",
"author_id": 64332,
"author_profile": "https://wordpress.stackexchange.com/users/64332",
"pm_score": 2,
"selected": true,
"text": "<p>I solved this and I only use:</p>\n\n<pre><code>wp_login_form();\n</code></pre>\n\n<p>Since I don't want users to get access to the wp-admin area at all I use the following code:</p>\n\n<pre><code>// Restrict users from accessing the admin-area\nfunction restrict_admin()\n{\n if ( ! current_user_can( 'manage_sites' ) ) {\n wp_redirect( site_url() );\n }\n}\nadd_action( 'admin_init', 'restrict_admin', 1 );\n\n// Disable admin-bar for users\nadd_action('after_setup_theme', 'remove_admin_bar');\n\nfunction remove_admin_bar() {\n if (!current_user_can('manage_sites') && !is_admin()) {\n show_admin_bar(false);\n }\n}\n</code></pre>\n\n<p>Kind regards\nJohan</p>\n"
},
{
"answer_id": 274265,
"author": "Gustavo Vill",
"author_id": 109983,
"author_profile": "https://wordpress.stackexchange.com/users/109983",
"pm_score": -1,
"selected": false,
"text": "<p>And what if you have a custom link and you want your users to be redirected there?\nI used \"clean login\" plugin and users are redirected to the custom link, but not of their sites.\nExample i want them to be redirected to www.site.com/user-page/custom-dashboard</p>\n\n<p>But with clean login or others plugins I can only get them to www.site.com/custom-dashboard</p>\n\n<p>So I can not redirect them from the main site to their sites </p>\n"
}
] |
2015/09/05
|
[
"https://wordpress.stackexchange.com/questions/201756",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64332/"
] |
On the multisite main page (<http://example.com/>) I have a login-form where users can login to their multisite like so:
```
<?php
$args = array(
'redirect' => get_active_blog_for_user(),
);
wp_login_form( $args );
?>
```
After logging in they will be redirected to their dashboard (http:// example.com/userblog/wp-admin/). I don't want them to be redirected to their dashboard. I want them to be redirected to their mainpage instead (<http://example.com/userblog/>). How can I achieve this?
Kind regards
Johan
|
I solved this and I only use:
```
wp_login_form();
```
Since I don't want users to get access to the wp-admin area at all I use the following code:
```
// Restrict users from accessing the admin-area
function restrict_admin()
{
if ( ! current_user_can( 'manage_sites' ) ) {
wp_redirect( site_url() );
}
}
add_action( 'admin_init', 'restrict_admin', 1 );
// Disable admin-bar for users
add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('manage_sites') && !is_admin()) {
show_admin_bar(false);
}
}
```
Kind regards
Johan
|
201,772 |
<p>I used a theme that had a great function for popup windows - a pop could be created by adding "#iframe" to any urllink ie</p>
<pre><code><a href="http://yahoo.com#iframe">click for popup</a>
</code></pre>
<p>Is there a function I can add to achieve this in any theme?</p>
<p>Second - is there an easy way to do popups containing html instead of a url?</p>
|
[
{
"answer_id": 202493,
"author": "Johan Ndiyo Linnarsson",
"author_id": 64332,
"author_profile": "https://wordpress.stackexchange.com/users/64332",
"pm_score": 2,
"selected": true,
"text": "<p>I solved this and I only use:</p>\n\n<pre><code>wp_login_form();\n</code></pre>\n\n<p>Since I don't want users to get access to the wp-admin area at all I use the following code:</p>\n\n<pre><code>// Restrict users from accessing the admin-area\nfunction restrict_admin()\n{\n if ( ! current_user_can( 'manage_sites' ) ) {\n wp_redirect( site_url() );\n }\n}\nadd_action( 'admin_init', 'restrict_admin', 1 );\n\n// Disable admin-bar for users\nadd_action('after_setup_theme', 'remove_admin_bar');\n\nfunction remove_admin_bar() {\n if (!current_user_can('manage_sites') && !is_admin()) {\n show_admin_bar(false);\n }\n}\n</code></pre>\n\n<p>Kind regards\nJohan</p>\n"
},
{
"answer_id": 274265,
"author": "Gustavo Vill",
"author_id": 109983,
"author_profile": "https://wordpress.stackexchange.com/users/109983",
"pm_score": -1,
"selected": false,
"text": "<p>And what if you have a custom link and you want your users to be redirected there?\nI used \"clean login\" plugin and users are redirected to the custom link, but not of their sites.\nExample i want them to be redirected to www.site.com/user-page/custom-dashboard</p>\n\n<p>But with clean login or others plugins I can only get them to www.site.com/custom-dashboard</p>\n\n<p>So I can not redirect them from the main site to their sites </p>\n"
}
] |
2015/09/05
|
[
"https://wordpress.stackexchange.com/questions/201772",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66990/"
] |
I used a theme that had a great function for popup windows - a pop could be created by adding "#iframe" to any urllink ie
```
<a href="http://yahoo.com#iframe">click for popup</a>
```
Is there a function I can add to achieve this in any theme?
Second - is there an easy way to do popups containing html instead of a url?
|
I solved this and I only use:
```
wp_login_form();
```
Since I don't want users to get access to the wp-admin area at all I use the following code:
```
// Restrict users from accessing the admin-area
function restrict_admin()
{
if ( ! current_user_can( 'manage_sites' ) ) {
wp_redirect( site_url() );
}
}
add_action( 'admin_init', 'restrict_admin', 1 );
// Disable admin-bar for users
add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('manage_sites') && !is_admin()) {
show_admin_bar(false);
}
}
```
Kind regards
Johan
|
201,786 |
<p>I need to add a php code in a wordpress widget called PHP Code Widget which only asks for proper enclosing:</p>
<p>All PHP code must be enclosed in the standard php opening and closing tags ( <code><?php</code> and <code>?></code> ) for it to be recognized and executed.</p>
<p>The code must use the current page title slug (i will use PAGES not posts) to look if in the upload folder there is any .jpg image named after the current page title SLUG. If there is such image, then it shows it:</p>
<pre><code><img src="current-page-name-slug.jpg" alt="current page title" height="image-height" width="image-width">
</code></pre>
<p>As you can see it must also use current page title for the image alt. And if possible, to retrieve image height and width and put them in their html parts. However this last one is not a must as i can manually resize all images to the same size and leave those fixed.</p>
<p>So the more or less pseudo code would be something like:</p>
<pre><code>php start
IF file exists uploads/current-page-slug.jpg
then
<img src="current-page-name-slug.jpg" alt="current page title" height="image-height" width="image-width">
else
do nothing
php end
</code></pre>
<p>Ive read a bit about the wordpress loop, and im not sure if current page slug and current page title are reacheable from a sidebar widget.</p>
<p>Give me a hand please.</p>
<p>Update:</p>
<p>I have tried bklynM code. It is not working and when looking in the page sourcecode to see what is going this is what i find:</p>
<p><code><aside id="execphp-3" class="widget widget_execphp"><h3 class="widget-title">Image:</h3> <div class="execphpwidget"><img src="//www.yourdomain.com/wp-content/uploads/$slug" title="<?php the_title_attribute(); ?>" alt="" ></div>
</aside></code></p>
<p>(ive edited domain name to keep it private) In my understanding the code is mostly not being evaluated. Base url is evaluated, but the:</p>
<p>$slug
and</p>
<p>are untouched. Do you have any idea if maybe the plugin is preventing it from working. Also i use w3c total cache. Ive also updated my question to let clear that the img folder is fixed and images are not attached to posts in any way, only bulk uploaded through ftp to that folder. This is a way to programatically look if there is an image with the same permalink name (also called slug) that the page (again i dont use posts, i only use pages).What may am i missing here.</p>
<p>Update for bklinM:</p>
<p>Thank you very much this is working. However it does not excludes when there is no file so it shows an error on those situations. Ive read through link ive tried to add an else, to change it to a if_file_exists, to an is_file, and many other but they only break the code. Do you have any idea how to change the code so it does work only when it finds an image or an existing url to that file, so when there is no file no img html is shown. – Zacocom Zaccom</p>
|
[
{
"answer_id": 202493,
"author": "Johan Ndiyo Linnarsson",
"author_id": 64332,
"author_profile": "https://wordpress.stackexchange.com/users/64332",
"pm_score": 2,
"selected": true,
"text": "<p>I solved this and I only use:</p>\n\n<pre><code>wp_login_form();\n</code></pre>\n\n<p>Since I don't want users to get access to the wp-admin area at all I use the following code:</p>\n\n<pre><code>// Restrict users from accessing the admin-area\nfunction restrict_admin()\n{\n if ( ! current_user_can( 'manage_sites' ) ) {\n wp_redirect( site_url() );\n }\n}\nadd_action( 'admin_init', 'restrict_admin', 1 );\n\n// Disable admin-bar for users\nadd_action('after_setup_theme', 'remove_admin_bar');\n\nfunction remove_admin_bar() {\n if (!current_user_can('manage_sites') && !is_admin()) {\n show_admin_bar(false);\n }\n}\n</code></pre>\n\n<p>Kind regards\nJohan</p>\n"
},
{
"answer_id": 274265,
"author": "Gustavo Vill",
"author_id": 109983,
"author_profile": "https://wordpress.stackexchange.com/users/109983",
"pm_score": -1,
"selected": false,
"text": "<p>And what if you have a custom link and you want your users to be redirected there?\nI used \"clean login\" plugin and users are redirected to the custom link, but not of their sites.\nExample i want them to be redirected to www.site.com/user-page/custom-dashboard</p>\n\n<p>But with clean login or others plugins I can only get them to www.site.com/custom-dashboard</p>\n\n<p>So I can not redirect them from the main site to their sites </p>\n"
}
] |
2015/09/05
|
[
"https://wordpress.stackexchange.com/questions/201786",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79929/"
] |
I need to add a php code in a wordpress widget called PHP Code Widget which only asks for proper enclosing:
All PHP code must be enclosed in the standard php opening and closing tags ( `<?php` and `?>` ) for it to be recognized and executed.
The code must use the current page title slug (i will use PAGES not posts) to look if in the upload folder there is any .jpg image named after the current page title SLUG. If there is such image, then it shows it:
```
<img src="current-page-name-slug.jpg" alt="current page title" height="image-height" width="image-width">
```
As you can see it must also use current page title for the image alt. And if possible, to retrieve image height and width and put them in their html parts. However this last one is not a must as i can manually resize all images to the same size and leave those fixed.
So the more or less pseudo code would be something like:
```
php start
IF file exists uploads/current-page-slug.jpg
then
<img src="current-page-name-slug.jpg" alt="current page title" height="image-height" width="image-width">
else
do nothing
php end
```
Ive read a bit about the wordpress loop, and im not sure if current page slug and current page title are reacheable from a sidebar widget.
Give me a hand please.
Update:
I have tried bklynM code. It is not working and when looking in the page sourcecode to see what is going this is what i find:
`<aside id="execphp-3" class="widget widget_execphp"><h3 class="widget-title">Image:</h3> <div class="execphpwidget"><img src="//www.yourdomain.com/wp-content/uploads/$slug" title="<?php the_title_attribute(); ?>" alt="" ></div>
</aside>`
(ive edited domain name to keep it private) In my understanding the code is mostly not being evaluated. Base url is evaluated, but the:
$slug
and
are untouched. Do you have any idea if maybe the plugin is preventing it from working. Also i use w3c total cache. Ive also updated my question to let clear that the img folder is fixed and images are not attached to posts in any way, only bulk uploaded through ftp to that folder. This is a way to programatically look if there is an image with the same permalink name (also called slug) that the page (again i dont use posts, i only use pages).What may am i missing here.
Update for bklinM:
Thank you very much this is working. However it does not excludes when there is no file so it shows an error on those situations. Ive read through link ive tried to add an else, to change it to a if\_file\_exists, to an is\_file, and many other but they only break the code. Do you have any idea how to change the code so it does work only when it finds an image or an existing url to that file, so when there is no file no img html is shown. – Zacocom Zaccom
|
I solved this and I only use:
```
wp_login_form();
```
Since I don't want users to get access to the wp-admin area at all I use the following code:
```
// Restrict users from accessing the admin-area
function restrict_admin()
{
if ( ! current_user_can( 'manage_sites' ) ) {
wp_redirect( site_url() );
}
}
add_action( 'admin_init', 'restrict_admin', 1 );
// Disable admin-bar for users
add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('manage_sites') && !is_admin()) {
show_admin_bar(false);
}
}
```
Kind regards
Johan
|
201,791 |
<p>I am trying to learn WP Theme development. And I am wondering what's the proper way to load api's? For example Google Maps:</p>
<p><code><script src="http://maps.googleapis.com/maps/api/js"></script></code></p>
<p>Should I enqueue the API url, or how should I do? I am a bit confused since this api for example reffers to a /js folder and not a direct script?</p>
|
[
{
"answer_id": 202493,
"author": "Johan Ndiyo Linnarsson",
"author_id": 64332,
"author_profile": "https://wordpress.stackexchange.com/users/64332",
"pm_score": 2,
"selected": true,
"text": "<p>I solved this and I only use:</p>\n\n<pre><code>wp_login_form();\n</code></pre>\n\n<p>Since I don't want users to get access to the wp-admin area at all I use the following code:</p>\n\n<pre><code>// Restrict users from accessing the admin-area\nfunction restrict_admin()\n{\n if ( ! current_user_can( 'manage_sites' ) ) {\n wp_redirect( site_url() );\n }\n}\nadd_action( 'admin_init', 'restrict_admin', 1 );\n\n// Disable admin-bar for users\nadd_action('after_setup_theme', 'remove_admin_bar');\n\nfunction remove_admin_bar() {\n if (!current_user_can('manage_sites') && !is_admin()) {\n show_admin_bar(false);\n }\n}\n</code></pre>\n\n<p>Kind regards\nJohan</p>\n"
},
{
"answer_id": 274265,
"author": "Gustavo Vill",
"author_id": 109983,
"author_profile": "https://wordpress.stackexchange.com/users/109983",
"pm_score": -1,
"selected": false,
"text": "<p>And what if you have a custom link and you want your users to be redirected there?\nI used \"clean login\" plugin and users are redirected to the custom link, but not of their sites.\nExample i want them to be redirected to www.site.com/user-page/custom-dashboard</p>\n\n<p>But with clean login or others plugins I can only get them to www.site.com/custom-dashboard</p>\n\n<p>So I can not redirect them from the main site to their sites </p>\n"
}
] |
2015/09/05
|
[
"https://wordpress.stackexchange.com/questions/201791",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66256/"
] |
I am trying to learn WP Theme development. And I am wondering what's the proper way to load api's? For example Google Maps:
`<script src="http://maps.googleapis.com/maps/api/js"></script>`
Should I enqueue the API url, or how should I do? I am a bit confused since this api for example reffers to a /js folder and not a direct script?
|
I solved this and I only use:
```
wp_login_form();
```
Since I don't want users to get access to the wp-admin area at all I use the following code:
```
// Restrict users from accessing the admin-area
function restrict_admin()
{
if ( ! current_user_can( 'manage_sites' ) ) {
wp_redirect( site_url() );
}
}
add_action( 'admin_init', 'restrict_admin', 1 );
// Disable admin-bar for users
add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('manage_sites') && !is_admin()) {
show_admin_bar(false);
}
}
```
Kind regards
Johan
|
201,793 |
<p>I need to get the post author profile picture link.</p>
<p>I know I can use <code>get_avatar();</code> but it displays whole image markup</p>
<pre><code><img src="http://.../img.png" class="avatar img-responsive" alt="image">
</code></pre>
<p>But need only the <code>src</code> of the author profile pic.</p>
<p>How can I got that ? Maybe we can use some <code>php</code> or <code>js</code> to take out the only <code>src</code> value from the total output.</p>
<p>My second question is, how can I add that <code>image</code> as <code>post_thumbnail</code> if no thumbnail exist for that post ?</p>
|
[
{
"answer_id": 201799,
"author": "Jentan Bernardus",
"author_id": 34502,
"author_profile": "https://wordpress.stackexchange.com/users/34502",
"pm_score": 0,
"selected": false,
"text": "<p>Beside using <code>get_avatar_url</code>, you can still use <code>get_avatar</code>. If I'm not wrong, this is what you're looking for.</p>\n\n<h2>Question 1</h2>\n\n<p>Get the post author profile picture link</p>\n\n<hr>\n\n<pre><code><?php \n // only output if gravatar function exists\n if (function_exists('get_avatar')) { ?>\n\n <?php\n // Convert email into md5 hash and set image size to 32px\n $gravatar = 'http://www.gravatar.com/avatar/' . md5(strtolower($user_email)) . '&s=32';\n\n // Convert email into md5 hash and remove image size to use as post image\n $gravatar_bg = 'http://www.gravatar.com/avatar/' . md5(strtolower($user_email)) . '';\n ?>\n <!-- Output the gravatar as img src -->\n <img src=\"<?php echo \"$gravatar\";?>\" alt=\"\">\n\n <!-- Output the gravatar as background url -->\n <div class=\"avatar\" style=\"background: url(<?php echo $gravatar_bg ?>);\" ></div>\n\n<?php } ?>\n</code></pre>\n\n<h2>Question 2</h2>\n\n<p>Add that image as post_thumbnail if no thumbnail exist for that post</p>\n\n<hr>\n\n<pre><code><?php\n // Check if post has thumbnail \n // if ( has_post_thumbnail() ) { // option 1\n if ( '' != get_the_post_thumbnail() ) { // option 2\n\n // if has, output the thumbnail\n the_post_thumbnail();\n\n } else {\n // if not, show the gravatar image\n echo '<img src=\"<?php echo \"$gravatar\";?>\" alt=\"\">';\n }\n?>\n</code></pre>\n\n<p>Hope this helps, good luck!</p>\n\n<hr>\n\n<p><em>Resources: <a href=\"http://codex.wordpress.org/Using_Gravatars\" rel=\"nofollow\">Using Gravatars</a> | <a href=\"https://developer.wordpress.org/reference/functions/has_post_thumbnail/\" rel=\"nofollow\">hast_post_thumbnail</a></em></p>\n"
},
{
"answer_id": 246477,
"author": "Vinit Patil",
"author_id": 107172,
"author_profile": "https://wordpress.stackexchange.com/users/107172",
"pm_score": 1,
"selected": false,
"text": "<p>just use the function get_avatart_uri() and pass in the user's email as the parameter it will give you the avatar image url</p>\n"
},
{
"answer_id": 261826,
"author": "Abdul Awal Uzzal",
"author_id": 31449,
"author_profile": "https://wordpress.stackexchange.com/users/31449",
"pm_score": 3,
"selected": false,
"text": "<p>Putting the following inside loop should fulfill your needs:</p>\n\n<pre><code><?php\n$get_author_id = get_the_author_meta('ID');\n$get_author_gravatar = get_avatar_url($get_author_id, array('size' => 450));\n\nif(has_post_thumbnail()){\n the_post_thumbnail();\n} else {\n echo '<img src=\"'.$get_author_gravatar.'\" alt=\"'.get_the_title().'\" />';\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 388135,
"author": "Abhishek Sachan",
"author_id": 149141,
"author_profile": "https://wordpress.stackexchange.com/users/149141",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p><strong>UPDATE(22 May, 2021)</strong> - <em>I am using a plugin <a href=\"https://wordpress.org/plugins/simple-local-avatars/\" rel=\"nofollow noreferrer\">Simple Local Avatars</a> to allow users to update images locally. The below\nsolution will only work if you use this plugin.</em></p>\n</blockquote>\n<hr />\n<p>Just In case someone is looking for full image of author and not finding it. Here is a little hack.</p>\n<h2>Simple Method</h2>\n<pre><code>$avatar_url = get_avatar_url( $author_id ); //this will give 96x96 image.\n$final_url = str_replace('-96x96.', '.',$author_avatar_url);\n</code></pre>\n<p>Replacing the <code>-96x96.</code> with just a <code>.</code>, Just need to make sure Image name doesn't include this string. Alternatively you can look for the same string from reverse and do the replace using <code>substr_replace()</code> like:</p>\n<h2>More Accurate Method</h2>\n<pre><code>$avatar_url = get_avatar_url( $author_id ); //this will give 96x96 image.\n$replace = '-96x96.';\n$pos = strpos($avatar_url, $replace, -(strlen($replace)+5)); // +5 for length of ext\n$final_url = substr_replace($avatar_url, '.', $pos, strlen($replace));\n</code></pre>\n<hr />\n<p><em>This is the first result on google while looking for full image of author so it might help someone.</em></p>\n"
},
{
"answer_id": 396525,
"author": "Ben Andrews ",
"author_id": 213268,
"author_profile": "https://wordpress.stackexchange.com/users/213268",
"pm_score": 0,
"selected": false,
"text": "<p>This is all I do to add the registered user's avatar.</p>\n<pre><code><img src="<?php echo get_avatar_url(get_the_author_meta('ID')); ?>" class="YOUR CSS CLASS">\n</code></pre>\n"
}
] |
2015/09/05
|
[
"https://wordpress.stackexchange.com/questions/201793",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65568/"
] |
I need to get the post author profile picture link.
I know I can use `get_avatar();` but it displays whole image markup
```
<img src="http://.../img.png" class="avatar img-responsive" alt="image">
```
But need only the `src` of the author profile pic.
How can I got that ? Maybe we can use some `php` or `js` to take out the only `src` value from the total output.
My second question is, how can I add that `image` as `post_thumbnail` if no thumbnail exist for that post ?
|
Putting the following inside loop should fulfill your needs:
```
<?php
$get_author_id = get_the_author_meta('ID');
$get_author_gravatar = get_avatar_url($get_author_id, array('size' => 450));
if(has_post_thumbnail()){
the_post_thumbnail();
} else {
echo '<img src="'.$get_author_gravatar.'" alt="'.get_the_title().'" />';
}
?>
```
|
201,814 |
<p>I would like to change jetpack default blank.jpg atribute on og:image.
I readed some artcile in this subject, but not realy helped me.
Here some trys:</p>
<pre><code>/**
* Override the default OpenGraph tags
*/
add_filter( 'jetpack_open_graph_tags', function( $tags ) {
$tags['twitter:site'] = '@ourhandle';
$tags['twitter:creator'] = '@ourhandle';
$tags['og:site_name'] = 'Our Site Name';
// the og:image key defaults to the featured image. if the value is
// not set, define it as an array. if the value is set, assume it is
// the featured image (or has been previously filtered)
if ( ! isset( $tags['og:image'] ) ) {
$tags['og:image'] = array();
}
$tags['og:image'] = (array)$tags['og:image'];
if ( is_a_particular_blog() ) {
$blog = custom_get_blog();
$tags['og:image'][] = custom_the_term_image_src( $blog-&gt;term_taxonomy_id );
} else {
foreach ( get_coauthors() as $coauthor ) {
$tags['og:image'][] = custom_get_coauthor_avatar_uri( $coauthor-&gt;ID, true );
}
}
$tags['og:image'][] = 'http://static.oursite.org/images/oursite_opengraph_360x185.png';
return $tags;
} );
function fix_jp_og_bugs ($og_tags)
{
$og_tags['twitter:site'] = '@laszlop';
if (0 == strcmp ($og_tags['og:image'],
"https://s0.wp.com/i/blank.jpg")
{
unset ($og_tags['og:image']);
}
return $og_tags;
}
add_filter ('jetpack_open_graph_tags', 'fix_jp_og_bugs', 11);
</code></pre>
<p>So I would like to see this meta tag on homepage:</p>
<pre><code><meta property="og:image" content="http://www.neocsatblog.mblx.hu/wp-content/uploads/2013/04/cropped-jobbbföld-maszk-21.png" />
</code></pre>
<p>And not this:</p>
<pre><code><meta property="og:image" content="https://s0.wp.com/i/blank.jpg" />
</code></pre>
<p>I use Ifeature theme with latest wordpress and jetpack plugin.<br>
My site is:<br>
<a href="http://neocsatblog.mblx.hu/" rel="nofollow">http://neocsatblog.mblx.hu/</a></p>
|
[
{
"answer_id": 201825,
"author": "Otto",
"author_id": 2232,
"author_profile": "https://wordpress.stackexchange.com/users/2232",
"pm_score": 1,
"selected": false,
"text": "<p>You made that <em>way</em> more complicated than it needs to be.</p>\n\n<pre><code>add_filter( 'jetpack_open_graph_image_default', 'example_change_default_image' );\nfunction example_change_default_image( $image ) {\n return 'https://s0.wp.com/i/blank.jpg';\n}\n</code></pre>\n\n<p>Just edit the function to return whatever URL you want.</p>\n"
},
{
"answer_id": 220251,
"author": "Gaia",
"author_id": 5090,
"author_profile": "https://wordpress.stackexchange.com/users/5090",
"pm_score": 0,
"selected": false,
"text": "<p>This is the <a href=\"http://jetpack.com/2013/07/12/add-a-default-image-open-graph-tag-on-home-page/\" rel=\"nofollow\">official way to do it</a></p>\n\n<p><strong>Create a 200x200 image and place it in a publicly accessible URL in your site.</strong> Best way to do this is to use Wordpress' built in media uploader.</p>\n\n<p>Then add to your theme’s functions.php file one of the following snippets:</p>\n\n<p>A) <strong>for making the chosen image show up on the home page:</strong></p>\n\n<pre><code>function fb_home_image( $tags ) {\n if ( is_home() || is_front_page() ) {\n // Remove the default blank image added by Jetpack\n unset( $tags['og:image'] );\n\n $fb_home_img = 'YOUR_IMAGE_URL';\n $tags['og:image'] = esc_url( $fb_home_img );\n }\n return $tags;\n}\nadd_filter( 'jetpack_open_graph_tags', 'fb_home_image' );\n</code></pre>\n\n<p>B) <strong>for making the chosen image show up on any page that doesn't have a featured image:</strong></p>\n\n<pre><code>function custom_jetpack_default_image() {\n return 'YOUR_IMAGE_URL';\n}\nadd_filter( 'jetpack_open_graph_image_default', 'custom_jetpack_default_image' );\n</code></pre>\n"
},
{
"answer_id": 249027,
"author": "whakawaehere",
"author_id": 78660,
"author_profile": "https://wordpress.stackexchange.com/users/78660",
"pm_score": 0,
"selected": false,
"text": "<p>I'm going to agree with Otto on the proper (and super simple) way of doing this, and add to it that this is the default override for og:description ...</p>\n\n<p><code>add_filter( 'jetpack_open_graph_fallback_description', 'change_default_description' );\nfunction change_default_description( $data ) {\n return 'Put your default descriptions here';\n}</code></p>\n"
}
] |
2015/09/06
|
[
"https://wordpress.stackexchange.com/questions/201814",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79944/"
] |
I would like to change jetpack default blank.jpg atribute on og:image.
I readed some artcile in this subject, but not realy helped me.
Here some trys:
```
/**
* Override the default OpenGraph tags
*/
add_filter( 'jetpack_open_graph_tags', function( $tags ) {
$tags['twitter:site'] = '@ourhandle';
$tags['twitter:creator'] = '@ourhandle';
$tags['og:site_name'] = 'Our Site Name';
// the og:image key defaults to the featured image. if the value is
// not set, define it as an array. if the value is set, assume it is
// the featured image (or has been previously filtered)
if ( ! isset( $tags['og:image'] ) ) {
$tags['og:image'] = array();
}
$tags['og:image'] = (array)$tags['og:image'];
if ( is_a_particular_blog() ) {
$blog = custom_get_blog();
$tags['og:image'][] = custom_the_term_image_src( $blog->term_taxonomy_id );
} else {
foreach ( get_coauthors() as $coauthor ) {
$tags['og:image'][] = custom_get_coauthor_avatar_uri( $coauthor->ID, true );
}
}
$tags['og:image'][] = 'http://static.oursite.org/images/oursite_opengraph_360x185.png';
return $tags;
} );
function fix_jp_og_bugs ($og_tags)
{
$og_tags['twitter:site'] = '@laszlop';
if (0 == strcmp ($og_tags['og:image'],
"https://s0.wp.com/i/blank.jpg")
{
unset ($og_tags['og:image']);
}
return $og_tags;
}
add_filter ('jetpack_open_graph_tags', 'fix_jp_og_bugs', 11);
```
So I would like to see this meta tag on homepage:
```
<meta property="og:image" content="http://www.neocsatblog.mblx.hu/wp-content/uploads/2013/04/cropped-jobbbföld-maszk-21.png" />
```
And not this:
```
<meta property="og:image" content="https://s0.wp.com/i/blank.jpg" />
```
I use Ifeature theme with latest wordpress and jetpack plugin.
My site is:
<http://neocsatblog.mblx.hu/>
|
You made that *way* more complicated than it needs to be.
```
add_filter( 'jetpack_open_graph_image_default', 'example_change_default_image' );
function example_change_default_image( $image ) {
return 'https://s0.wp.com/i/blank.jpg';
}
```
Just edit the function to return whatever URL you want.
|
201,815 |
<p>I'm trying to add a <a href="https://trinket.io/" rel="nofollow">trinket.io</a> widget to my blog post in order to do some interactive things but I'm not having any success.</p>
<p>If i try to just use the embed code given to me by the trinket.io page:</p>
<pre><code><iframe src="https://trinket.io/embed/python/73f4d9630f" width="100%"
height="356" frameborder="0" marginwidth="0" marginheight="0"
allowfullscreen></iframe>
</code></pre>
<p>All i get is just a link to the widget like this:</p>
<p><a href="https://trinket.io/embed/python/73f4d9630f" rel="nofollow">https://trinket.io/embed/python/73f4d9630f</a></p>
<p>Is there any way to actually get the python code and its output onto the blog-post ??</p>
|
[
{
"answer_id": 201825,
"author": "Otto",
"author_id": 2232,
"author_profile": "https://wordpress.stackexchange.com/users/2232",
"pm_score": 1,
"selected": false,
"text": "<p>You made that <em>way</em> more complicated than it needs to be.</p>\n\n<pre><code>add_filter( 'jetpack_open_graph_image_default', 'example_change_default_image' );\nfunction example_change_default_image( $image ) {\n return 'https://s0.wp.com/i/blank.jpg';\n}\n</code></pre>\n\n<p>Just edit the function to return whatever URL you want.</p>\n"
},
{
"answer_id": 220251,
"author": "Gaia",
"author_id": 5090,
"author_profile": "https://wordpress.stackexchange.com/users/5090",
"pm_score": 0,
"selected": false,
"text": "<p>This is the <a href=\"http://jetpack.com/2013/07/12/add-a-default-image-open-graph-tag-on-home-page/\" rel=\"nofollow\">official way to do it</a></p>\n\n<p><strong>Create a 200x200 image and place it in a publicly accessible URL in your site.</strong> Best way to do this is to use Wordpress' built in media uploader.</p>\n\n<p>Then add to your theme’s functions.php file one of the following snippets:</p>\n\n<p>A) <strong>for making the chosen image show up on the home page:</strong></p>\n\n<pre><code>function fb_home_image( $tags ) {\n if ( is_home() || is_front_page() ) {\n // Remove the default blank image added by Jetpack\n unset( $tags['og:image'] );\n\n $fb_home_img = 'YOUR_IMAGE_URL';\n $tags['og:image'] = esc_url( $fb_home_img );\n }\n return $tags;\n}\nadd_filter( 'jetpack_open_graph_tags', 'fb_home_image' );\n</code></pre>\n\n<p>B) <strong>for making the chosen image show up on any page that doesn't have a featured image:</strong></p>\n\n<pre><code>function custom_jetpack_default_image() {\n return 'YOUR_IMAGE_URL';\n}\nadd_filter( 'jetpack_open_graph_image_default', 'custom_jetpack_default_image' );\n</code></pre>\n"
},
{
"answer_id": 249027,
"author": "whakawaehere",
"author_id": 78660,
"author_profile": "https://wordpress.stackexchange.com/users/78660",
"pm_score": 0,
"selected": false,
"text": "<p>I'm going to agree with Otto on the proper (and super simple) way of doing this, and add to it that this is the default override for og:description ...</p>\n\n<p><code>add_filter( 'jetpack_open_graph_fallback_description', 'change_default_description' );\nfunction change_default_description( $data ) {\n return 'Put your default descriptions here';\n}</code></p>\n"
}
] |
2015/09/06
|
[
"https://wordpress.stackexchange.com/questions/201815",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79946/"
] |
I'm trying to add a [trinket.io](https://trinket.io/) widget to my blog post in order to do some interactive things but I'm not having any success.
If i try to just use the embed code given to me by the trinket.io page:
```
<iframe src="https://trinket.io/embed/python/73f4d9630f" width="100%"
height="356" frameborder="0" marginwidth="0" marginheight="0"
allowfullscreen></iframe>
```
All i get is just a link to the widget like this:
<https://trinket.io/embed/python/73f4d9630f>
Is there any way to actually get the python code and its output onto the blog-post ??
|
You made that *way* more complicated than it needs to be.
```
add_filter( 'jetpack_open_graph_image_default', 'example_change_default_image' );
function example_change_default_image( $image ) {
return 'https://s0.wp.com/i/blank.jpg';
}
```
Just edit the function to return whatever URL you want.
|
201,824 |
<p>I trying to understand what is happening with the Wordpress theme that I am using. The menu is found on the right hand side of the page and when the window size is made smaller it changes to a single drop down from the middle (for smaller devices). On inspection I can see that there are various classes that seem to handle the appearance:</p>
<pre><code>.menu-toggle,
.main-small-navigation ul.nav-menu.toggled-on {
display: block;
background-color: #fff;
}
.navigation-main ul {
display: none;
}
.menu-toggle {
background-color: #FAFAFA;
border-top: 1px solid #F0F0F0;
box-shadow: 0 -1px 0 rgba(0, 0, 0, 0.15) inset;
color: #1e1e1e;
etc etc
}
</code></pre>
<p>When the screen size is reduced the main-small-navigation class is used and all is fine. When the screen is put back however the menu is not displayed correctly. </p>
<p>What I am trying to figure out is how any of this might be called when you change the size of the screen. I realise this might be a vague and possibly theme specific but any pointers as to what I should be looking for would be much appreciated.</p>
|
[
{
"answer_id": 201827,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>This is called responsive design and has nothing to do with Wordpress, it is an extension rule to media queries (<em><code>@media</code></em>) in CSS3. CSS is a browser/client side language which can determine window sizes and browser types, this is what is used to determine how a website should look at a specific window size or browser. This media queries, when specified in CSS, will be used to resize a specific item to the required set size accordingly</p>\n\n<p>Some themes also incorporate javascript together with CSS to display HTML selectors differently on different window sizes and browser types.</p>\n\n<p>I'm not going to go into more details as this really is not Wordpress specific, you should take your time to read up on responsive design and media queries</p>\n"
},
{
"answer_id": 201906,
"author": "iulia",
"author_id": 4747,
"author_profile": "https://wordpress.stackexchange.com/users/4747",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>@media</code> query is being used to change styles depending on window size.</p>\n\n<p>Example which changes the height of the masthead when the min-width of the window is 800px</p>\n\n<pre><code>@media only screen and (min-width: 800px){\n.masthead.shrink {\n height: 50px; \n}\n}\n</code></pre>\n\n<p>so you can check your css style and look for any @media queries and modify accordingly.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries\" rel=\"nofollow\">Further reading</a></p>\n"
}
] |
2015/09/06
|
[
"https://wordpress.stackexchange.com/questions/201824",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38223/"
] |
I trying to understand what is happening with the Wordpress theme that I am using. The menu is found on the right hand side of the page and when the window size is made smaller it changes to a single drop down from the middle (for smaller devices). On inspection I can see that there are various classes that seem to handle the appearance:
```
.menu-toggle,
.main-small-navigation ul.nav-menu.toggled-on {
display: block;
background-color: #fff;
}
.navigation-main ul {
display: none;
}
.menu-toggle {
background-color: #FAFAFA;
border-top: 1px solid #F0F0F0;
box-shadow: 0 -1px 0 rgba(0, 0, 0, 0.15) inset;
color: #1e1e1e;
etc etc
}
```
When the screen size is reduced the main-small-navigation class is used and all is fine. When the screen is put back however the menu is not displayed correctly.
What I am trying to figure out is how any of this might be called when you change the size of the screen. I realise this might be a vague and possibly theme specific but any pointers as to what I should be looking for would be much appreciated.
|
This is called responsive design and has nothing to do with Wordpress, it is an extension rule to media queries (*`@media`*) in CSS3. CSS is a browser/client side language which can determine window sizes and browser types, this is what is used to determine how a website should look at a specific window size or browser. This media queries, when specified in CSS, will be used to resize a specific item to the required set size accordingly
Some themes also incorporate javascript together with CSS to display HTML selectors differently on different window sizes and browser types.
I'm not going to go into more details as this really is not Wordpress specific, you should take your time to read up on responsive design and media queries
|
201,844 |
<p>i try show the_date with link to same date!</p>
<pre><code> <?php the_date('l j F Y', '<tr>
<th colspan="3"><a href="<?php the_date('Y/m/d'); ?>" rel="bookmark">', '</th>
</tr>'); ?>
</code></pre>
|
[
{
"answer_id": 201847,
"author": "Erfo",
"author_id": 41537,
"author_profile": "https://wordpress.stackexchange.com/users/41537",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code><?php \n$archive_year = get_the_time('Y'); \n$archive_month = get_the_time('m'); \n$archive_day = get_the_time('d'); \n?>\n<a href=\"<?php echo get_day_link( $archive_year, $archive_month, $archive_day); ?>\"><?php the_date('Y/m/d'); ?></a>\n</code></pre>\n\n<p>HTML result:</p>\n\n<pre><code><a href=\"http://example.com/2015/09/07\">2015/09/07</a>\n</code></pre>\n"
},
{
"answer_id": 202029,
"author": "Erfo",
"author_id": 41537,
"author_profile": "https://wordpress.stackexchange.com/users/41537",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php \n$archive_year = get_the_time('Y'); \n$archive_month = get_the_time('m'); \n$archive_day = get_the_time('d'); \n?>\n<a href=\"<?php echo get_day_link( $archive_year, $archive_month, $archive_day); ?>\"><?php the_date('Y/m/d'); ?></a>\n<a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n</code></pre>\n\n<p>HTML result:</p>\n\n<pre><code><a href=\"http://example.com/2015/09/07\">2015/09/07</a>\n<a href=\"http://example.com/title-post\">Title Post</a>\n</code></pre>\n\n<p>For example, if you want show the latest posts:</p>\n\n<pre><code>global $post;\n$post_args = array(\n 'posts_per_page' => 5\n);\n$the_query = new WP_Query( $post_args );\n\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n $archive_year = get_the_time('Y'); \n $archive_month = get_the_time('m'); \n $archive_day = get_the_time('d'); \n ?>\n <a href=\"<?php echo get_day_link( $archive_year, $archive_month, $archive_day); ?>\"><?php the_date('Y/m/d'); ?></a>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n }\nwp_reset_query();\n}\n</code></pre>\n"
}
] |
2015/09/06
|
[
"https://wordpress.stackexchange.com/questions/201844",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78599/"
] |
i try show the\_date with link to same date!
```
<?php the_date('l j F Y', '<tr>
<th colspan="3"><a href="<?php the_date('Y/m/d'); ?>" rel="bookmark">', '</th>
</tr>'); ?>
```
|
Try this:
```
<?php
$archive_year = get_the_time('Y');
$archive_month = get_the_time('m');
$archive_day = get_the_time('d');
?>
<a href="<?php echo get_day_link( $archive_year, $archive_month, $archive_day); ?>"><?php the_date('Y/m/d'); ?></a>
```
HTML result:
```
<a href="http://example.com/2015/09/07">2015/09/07</a>
```
|
201,849 |
<p>I'm using the MyStile theme for a new site. I'm trying to create a child theme so I can modify the theme and not have my changes overwritten, however once I activate my child theme, the whole styling seems to go from the website all together.<br>
I'm guessing the issue here lies somewhere when it's calling the parent <em>style.css</em> file.</p>
<p>Here's what I have in my child theme's <em>style.css</em>.</p>
<pre><code> /*
Theme Name: Blurred Edge Apparel
Theme URI: http://www.blurrededgeapparel.com
Description: MyStile Child Theme
Author: Blurred Edge Apparel
Author URI: http://www.blurrededgeapparel.com
Template: mystile
Version: 1.0.0
*/
@import url("../mystile/style.css");
</code></pre>
<p>I have also copied across <em>header.php</em> and <em>footer.php</em> from the parents theme directory, however still no joy. <br>
Am I missing something here?</p>
|
[
{
"answer_id": 201850,
"author": "d79",
"author_id": 69071,
"author_profile": "https://wordpress.stackexchange.com/users/69071",
"pm_score": 4,
"selected": true,
"text": "<p>Take a look at <a href=\"https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme\" rel=\"noreferrer\">How to create a Child Theme</a> and you'll see that:</p>\n\n<blockquote>\n <p>the previous method to enqueue the parent stylesheet was to import the parent theme stylesheet using @import: this is no longer best practice. The correct method of enqueuing the parent theme stylesheet is to add a wp_enqueue_scripts action and use wp_enqueue_style() in your child theme's functions.php.</p>\n</blockquote>\n\n<p>Here's the example provided:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\nfunction theme_enqueue_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n}\n</code></pre>\n"
},
{
"answer_id": 201890,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>The mystile theme is a 3 years old theme which is not simply ready to use as parent-style because the child-style is fixed in <strong>header.php</strong> at the bad place</p>\n\n<p>the quicker way to correct this, is to put theses files in the child-theme directory : </p>\n\n<ul>\n<li>file <strong>style.css</strong> : </li>\n</ul>\n\n<p>.</p>\n\n<pre><code>/*\nTemplate: mystile\n*/\n</code></pre>\n\n<ul>\n<li>file <strong>child-style.css</strong> : all the CSS rules that you want to apply</li>\n<li>file <strong>functions.php</strong> : </li>\n</ul>\n\n<p>.</p>\n\n<pre><code><?php\nadd_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\nfunction theme_enqueue_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n\n wp_enqueue_style( 'child-style'\n , get_stylesheet_directory_uri() . '/child-style.css'\n , array('parent-style') // declare the dependency\n // in order to load child-style after parent-style\n );\n}\n</code></pre>\n"
},
{
"answer_id": 380051,
"author": "Nick Rolando",
"author_id": 80972,
"author_profile": "https://wordpress.stackexchange.com/users/80972",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/advanced-topics/child-themes/</a></p>\n<blockquote>\n<p>The recommended way of enqueuing the stylesheets is to add a wp_enqueue_scripts action and use wp_enqueue_style() in your child theme’s functions.php.\nIf you do not have one, create a functions.php in your child theme’s directory. The first line of your child theme’s functions.php will be an opening PHP tag (<?php), after which you can write the PHP code according to what your parent theme does.</p>\n</blockquote>\n<blockquote>\n<p>If the parent theme loads both stylesheets, the child theme does not need to do anything.</p>\n</blockquote>\n<blockquote>\n<p><strong>If the parent theme loads its style using a function starting with get_template, such as get_template_directory() and get_template_directory_uri()</strong>, the child theme needs to load just the child styles, using the parent’s handle in the dependency parameter.</p>\n</blockquote>\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\nfunction my_theme_enqueue_styles() {\n wp_enqueue_style( 'child-style', get_stylesheet_uri(),\n array( 'parenthandle' ), \n wp_get_theme()->get('Version') // this only works if you have Version in the style header\n );\n}\n</code></pre>\n<blockquote>\n<p><strong>If the parent theme loads its style using a function starting with get_stylesheet, such as get_stylesheet_directory() and get_stylesheet_directory_uri()</strong>, the child theme needs to load both parent and child stylesheets. Be sure to use the same handle name as the parent does for the parent styles.</p>\n</blockquote>\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\nfunction my_theme_enqueue_styles() {\n $parenthandle = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.\n $theme = wp_get_theme();\n wp_enqueue_style( $parenthandle, get_template_directory_uri() . '/style.css', \n array(), // if the parent theme code has a dependency, copy it to here\n $theme->parent()->get('Version')\n );\n wp_enqueue_style( 'child-style', get_stylesheet_uri(),\n array( $parenthandle ),\n $theme->get('Version') // this only works if you have Version in the style header\n );\n}\n</code></pre>\n<p>See the quoted text I put in bold above. Now check how your parent theme is loading its style, and follow the instructions and example accordingly. Mine was the latter, thus I coded mine as such:</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'twentytwentychild_enqueue_styles' );\nfunction twentytwentychild_enqueue_styles() {\n $parentHandle = "twentytwenty-style";\n $childHandle = "twentytwentychild-style";\n $theme = wp_get_theme();\n\n wp_enqueue_style($parentHandle, get_template_directory_uri() . '/style.css',\n array(), // if the parent theme code has a dependency, copy it to here\n $theme->parent()->get('Version') // this only works if you have Version in the style header\n );\n\n wp_enqueue_style($childHandle, get_stylesheet_uri(),\n array($parentHandle),\n $theme->get('Version') // this only works if you have Version in the style header\n );\n}\n</code></pre>\n"
}
] |
2015/09/06
|
[
"https://wordpress.stackexchange.com/questions/201849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77340/"
] |
I'm using the MyStile theme for a new site. I'm trying to create a child theme so I can modify the theme and not have my changes overwritten, however once I activate my child theme, the whole styling seems to go from the website all together.
I'm guessing the issue here lies somewhere when it's calling the parent *style.css* file.
Here's what I have in my child theme's *style.css*.
```
/*
Theme Name: Blurred Edge Apparel
Theme URI: http://www.blurrededgeapparel.com
Description: MyStile Child Theme
Author: Blurred Edge Apparel
Author URI: http://www.blurrededgeapparel.com
Template: mystile
Version: 1.0.0
*/
@import url("../mystile/style.css");
```
I have also copied across *header.php* and *footer.php* from the parents theme directory, however still no joy.
Am I missing something here?
|
Take a look at [How to create a Child Theme](https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme) and you'll see that:
>
> the previous method to enqueue the parent stylesheet was to import the parent theme stylesheet using @import: this is no longer best practice. The correct method of enqueuing the parent theme stylesheet is to add a wp\_enqueue\_scripts action and use wp\_enqueue\_style() in your child theme's functions.php.
>
>
>
Here's the example provided:
```
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
```
|
201,871 |
<p>On a project I require to keep only 10 latest posts on website and auto delete all other posts. So I came up with this function which triggers on post publish/update and I used <code>offset</code> parameter to exclude latest 10 items.</p>
<pre><code>function wpse_auto_delete_posts( $post_ID ) {
global $post;
$delete_posts = get_posts( array( 'post_type' => 'post', 'offset' => 10, 'posts_per_page' => -1 ) );
foreach ( $delete_posts as $delete_post ) : setup_postdata( $delete_post );
wp_delete_post( $delete_post->ID, true );
endforeach;
wp_reset_postdata();
}
add_action( 'publish_post', 'wpse_auto_delete_posts' );
</code></pre>
<p>But it appears, <code>offset</code> didn't work here with <code>'posts_per_page' => -1</code> and it keeps deleting all posts. I thought of using Date query but it will also not work too because new posts are created very frequently.</p>
<p>Is there any way to select all posts except latest 10 or 5. So WordPress can process them and keep latest X posts.</p>
|
[
{
"answer_id": 201882,
"author": "Ignat B.",
"author_id": 38121,
"author_profile": "https://wordpress.stackexchange.com/users/38121",
"pm_score": 0,
"selected": false,
"text": "<p>The fact that <code>'nopaging' => true</code> and <code>'posts_per_page' => -1</code> behaves the same. This parameters are cancelling the <code>LIMIT</code> clause of MySQL request made by your WP.</p>\n\n<blockquote>\n <p>offset (int) - number of post to displace or pass over. Warning:\n Setting the offset parameter overrides/ignores the paged parameter and\n breaks pagination (Click here for a workaround). <strong>The 'offset'\n parameter is ignored when 'posts_per_page'=>-1 (show all posts) is\n used.</strong></p>\n</blockquote>\n\n<p>Considering the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html#id4651990\" rel=\"nofollow\">MySQL docs</a> and their recommendation, you can use a large number for <code>posts_per_page</code> parameter, leaving offset as it is.</p>\n\n<blockquote>\n <p>To retrieve all rows from a certain offset up to the end of the result\n set, you can use some large number for the second parameter. This\n statement retrieves all rows from the 96th row to the last:</p>\n \n <p><code>SELECT * FROM tbl LIMIT 95,18446744073709551615;</code></p>\n</blockquote>\n"
},
{
"answer_id": 201913,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>The <code>offset</code> parameter is ignored with <code>posts_per_page</code> set to <code>-1</code> in <code>WP_Query</code>. If you look at the source code in the <code>WP_Query</code> class, <code>posts_per_page=-1</code> sets <code>nopaging</code> to true.</p>\n\n<pre><code>if ( !isset($q['nopaging']) ) {\n if ( $q['posts_per_page'] == -1 ) {\n $q['nopaging'] = true;\n } else {\n $q['nopaging'] = false;\n }\n}\n</code></pre>\n\n<p>This in turn will not append the <code>LIMIT</code> to the SQL query (<em><code>empty($q['nopaging'] === false</code> which fail the conditional statement</em>) meaning that the whole pagination/offset is ignored and all posts are returned regardless</p>\n\n<pre><code>if ( empty($q['nopaging']) && !$this->is_singular ) {\n $page = absint($q['paged']);\n if ( !$page )\n $page = 1;\n\n if ( empty($q['offset']) ) {\n $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';\n } else { // we're ignoring $page and using 'offset'\n $q['offset'] = absint($q['offset']);\n $pgstrt = $q['offset'] . ', ';\n }\n $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];\n}\n</code></pre>\n\n<p>I think the best workaround here is to make use of normal PHP (<em><a href=\"http://php.net/manual/en/function.array-slice.php\"><code>array_slice()</code></a></em>)after getting all the posts. You want to get only post ID's here as <code>wp_delete_post</code> is quite expensive to run and only really need the post ID, so we don't need any other post info.</p>\n\n<p>In short, your query will look like this: (<strong><em>NOTE:</strong> This is all untested and needs PHP 5.4+</em>)</p>\n\n<pre><code>add_action( 'publish_post', function ( $post_ID ) \n{\n $args = [\n 'nopaging' => true,\n 'fields' => 'ids'\n ];\n $posts_array = get_posts( $args );\n // Make sure that we have post ID's returned\n if ( $posts_array ) {\n // Get all post ids after the 10th post using array_slice\n $delete_posts = array_slice( $posts_array, 10 );\n // Make sure that we actually have post ID's in the $delete_posts array\n if ( $delete_posts ) {\n foreach ( $delete_posts as $delete_post )\n wp_delete_post( $delete_post, true );\n }\n }\n});\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>Just before I forget, you can also define <code>posts_per_page</code> as an unlikely integer value instead of <code>-1</code>. This will also work with your code with the <code>offset</code> parameter set</p>\n"
}
] |
2015/09/07
|
[
"https://wordpress.stackexchange.com/questions/201871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22461/"
] |
On a project I require to keep only 10 latest posts on website and auto delete all other posts. So I came up with this function which triggers on post publish/update and I used `offset` parameter to exclude latest 10 items.
```
function wpse_auto_delete_posts( $post_ID ) {
global $post;
$delete_posts = get_posts( array( 'post_type' => 'post', 'offset' => 10, 'posts_per_page' => -1 ) );
foreach ( $delete_posts as $delete_post ) : setup_postdata( $delete_post );
wp_delete_post( $delete_post->ID, true );
endforeach;
wp_reset_postdata();
}
add_action( 'publish_post', 'wpse_auto_delete_posts' );
```
But it appears, `offset` didn't work here with `'posts_per_page' => -1` and it keeps deleting all posts. I thought of using Date query but it will also not work too because new posts are created very frequently.
Is there any way to select all posts except latest 10 or 5. So WordPress can process them and keep latest X posts.
|
The `offset` parameter is ignored with `posts_per_page` set to `-1` in `WP_Query`. If you look at the source code in the `WP_Query` class, `posts_per_page=-1` sets `nopaging` to true.
```
if ( !isset($q['nopaging']) ) {
if ( $q['posts_per_page'] == -1 ) {
$q['nopaging'] = true;
} else {
$q['nopaging'] = false;
}
}
```
This in turn will not append the `LIMIT` to the SQL query (*`empty($q['nopaging'] === false` which fail the conditional statement*) meaning that the whole pagination/offset is ignored and all posts are returned regardless
```
if ( empty($q['nopaging']) && !$this->is_singular ) {
$page = absint($q['paged']);
if ( !$page )
$page = 1;
if ( empty($q['offset']) ) {
$pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
} else { // we're ignoring $page and using 'offset'
$q['offset'] = absint($q['offset']);
$pgstrt = $q['offset'] . ', ';
}
$limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
}
```
I think the best workaround here is to make use of normal PHP (*[`array_slice()`](http://php.net/manual/en/function.array-slice.php)*)after getting all the posts. You want to get only post ID's here as `wp_delete_post` is quite expensive to run and only really need the post ID, so we don't need any other post info.
In short, your query will look like this: (***NOTE:*** This is all untested and needs PHP 5.4+)
```
add_action( 'publish_post', function ( $post_ID )
{
$args = [
'nopaging' => true,
'fields' => 'ids'
];
$posts_array = get_posts( $args );
// Make sure that we have post ID's returned
if ( $posts_array ) {
// Get all post ids after the 10th post using array_slice
$delete_posts = array_slice( $posts_array, 10 );
// Make sure that we actually have post ID's in the $delete_posts array
if ( $delete_posts ) {
foreach ( $delete_posts as $delete_post )
wp_delete_post( $delete_post, true );
}
}
});
```
**EDIT**
Just before I forget, you can also define `posts_per_page` as an unlikely integer value instead of `-1`. This will also work with your code with the `offset` parameter set
|
201,877 |
<p>I want my POST pagination to show the numbers from 1 to 9 like this:
01 02 03 04 05 06 07 08 09 10 11... and NOT like > 1, 2, 3, 4...</p>
<p>Actualy i have this code:</p>
<pre><code><?php wp_link_pages( array( 'before' => '
<div class="page-links clr">', 'after' => '</div>
', 'link_before' => '<span>', 'link_after' => '</span>' ) );?>
</code></pre>
|
[
{
"answer_id": 201894,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_link_pages\" rel=\"nofollow\"><code>wp_link_pages()</code></a> does not have a parameter for what you want. So I'm thinking you can make use of the filter hook <a href=\"https://developer.wordpress.org/reference/hooks/wp_link_pages_link/\" rel=\"nofollow\"><code>wp_link_pages_link</code></a>, which has two - <code>$link</code> and <code>$i</code> - parameters, where <code>$i</code> is the page number. You can use WordPress' <a href=\"https://codex.wordpress.org/Function_Reference/zeroise\" rel=\"nofollow\"><code>zeroise()</code></a> function to get the format you want.</p>\n"
},
{
"answer_id": 407715,
"author": "adrian proscinski",
"author_id": 224099,
"author_profile": "https://wordpress.stackexchange.com/users/224099",
"pm_score": 0,
"selected": false,
"text": "<p>Simple replace content in <code><a></a></code></p>\n<pre><code>function custom_pagination(){\n\n global $wp_query;\n $max_pages = $wp_query->max_num_pages;\n $current_page = !empty($wp_query->query_vars['paged']) ? $wp_query->query_vars['paged'] : 1;\n\n?>\n <nav class="pagination">\n<?php\n $big = 999999999;\n$paginate_links = paginate_links(array(...));\n\n$paterns = ['/\\>1\\<\\//', '/\\>2\\<\\//','/\\>3\\<\\//','/\\>4\\<\\//','/\\>5\\<\\//','/\\>6\\<\\//', '/\\>7\\<\\//','/\\>8\\<\\//','/\\>9\\<\\//'];\n $replacements = ['>01</', '>02</', '>03</', '>04</', '>05</', '>06</','>07</', '>08</', '>09</'];\n $paginate_links = preg_replace( $paterns, $replacements, $paginate_links );\n\nif ( $paginate_links ) {\n foreach( $paginate_links as $link )\n echo $link;\n}\n\n?>\n </nav>\n<?php\n}\n</code></pre>\n"
}
] |
2015/09/07
|
[
"https://wordpress.stackexchange.com/questions/201877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79974/"
] |
I want my POST pagination to show the numbers from 1 to 9 like this:
01 02 03 04 05 06 07 08 09 10 11... and NOT like > 1, 2, 3, 4...
Actualy i have this code:
```
<?php wp_link_pages( array( 'before' => '
<div class="page-links clr">', 'after' => '</div>
', 'link_before' => '<span>', 'link_after' => '</span>' ) );?>
```
|
[`wp_link_pages()`](https://codex.wordpress.org/Function_Reference/wp_link_pages) does not have a parameter for what you want. So I'm thinking you can make use of the filter hook [`wp_link_pages_link`](https://developer.wordpress.org/reference/hooks/wp_link_pages_link/), which has two - `$link` and `$i` - parameters, where `$i` is the page number. You can use WordPress' [`zeroise()`](https://codex.wordpress.org/Function_Reference/zeroise) function to get the format you want.
|
201,888 |
<p>This is what happens in a Wordpress (Woocommerce) site I've been asked to investigate.</p>
<p>1) I make a modification to .htaccess and save it.</p>
<p>Here's output of the ls -command</p>
<pre><code>% ls -l
ll
-r--r--r-- 1 user group 248 Sep 7 11:31 .htaccess
</code></pre>
<p>2) Just a moment later</p>
<pre><code>% ls -l
-r--r--r-- 1 user group 235 Jul 20 09:42 .htaccess
</code></pre>
<p>The changes have disappeared. Note the changed date in the file (apparently it is copied from somewhere).</p>
<p>What is causing this? And how do I stop it from happening?</p>
|
[
{
"answer_id": 201894,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_link_pages\" rel=\"nofollow\"><code>wp_link_pages()</code></a> does not have a parameter for what you want. So I'm thinking you can make use of the filter hook <a href=\"https://developer.wordpress.org/reference/hooks/wp_link_pages_link/\" rel=\"nofollow\"><code>wp_link_pages_link</code></a>, which has two - <code>$link</code> and <code>$i</code> - parameters, where <code>$i</code> is the page number. You can use WordPress' <a href=\"https://codex.wordpress.org/Function_Reference/zeroise\" rel=\"nofollow\"><code>zeroise()</code></a> function to get the format you want.</p>\n"
},
{
"answer_id": 407715,
"author": "adrian proscinski",
"author_id": 224099,
"author_profile": "https://wordpress.stackexchange.com/users/224099",
"pm_score": 0,
"selected": false,
"text": "<p>Simple replace content in <code><a></a></code></p>\n<pre><code>function custom_pagination(){\n\n global $wp_query;\n $max_pages = $wp_query->max_num_pages;\n $current_page = !empty($wp_query->query_vars['paged']) ? $wp_query->query_vars['paged'] : 1;\n\n?>\n <nav class="pagination">\n<?php\n $big = 999999999;\n$paginate_links = paginate_links(array(...));\n\n$paterns = ['/\\>1\\<\\//', '/\\>2\\<\\//','/\\>3\\<\\//','/\\>4\\<\\//','/\\>5\\<\\//','/\\>6\\<\\//', '/\\>7\\<\\//','/\\>8\\<\\//','/\\>9\\<\\//'];\n $replacements = ['>01</', '>02</', '>03</', '>04</', '>05</', '>06</','>07</', '>08</', '>09</'];\n $paginate_links = preg_replace( $paterns, $replacements, $paginate_links );\n\nif ( $paginate_links ) {\n foreach( $paginate_links as $link )\n echo $link;\n}\n\n?>\n </nav>\n<?php\n}\n</code></pre>\n"
}
] |
2015/09/07
|
[
"https://wordpress.stackexchange.com/questions/201888",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79979/"
] |
This is what happens in a Wordpress (Woocommerce) site I've been asked to investigate.
1) I make a modification to .htaccess and save it.
Here's output of the ls -command
```
% ls -l
ll
-r--r--r-- 1 user group 248 Sep 7 11:31 .htaccess
```
2) Just a moment later
```
% ls -l
-r--r--r-- 1 user group 235 Jul 20 09:42 .htaccess
```
The changes have disappeared. Note the changed date in the file (apparently it is copied from somewhere).
What is causing this? And how do I stop it from happening?
|
[`wp_link_pages()`](https://codex.wordpress.org/Function_Reference/wp_link_pages) does not have a parameter for what you want. So I'm thinking you can make use of the filter hook [`wp_link_pages_link`](https://developer.wordpress.org/reference/hooks/wp_link_pages_link/), which has two - `$link` and `$i` - parameters, where `$i` is the page number. You can use WordPress' [`zeroise()`](https://codex.wordpress.org/Function_Reference/zeroise) function to get the format you want.
|
201,922 |
<p>I've been using this code:</p>
<pre><code>function remove_first_image ($content) {
if (!is_page() && !is_feed() && !is_feed()) {
$content = preg_replace("/<img[^>]+\>/i", "", $content, 1);
} return $content;
}
add_filter('the_content', 'remove_first_image');
</code></pre>
<p>for a few years now on my site that has almost 20,000 posts with images inserted at the top. I have a plugin that uses the first image as a featured image as well. sometimes I need to still insert a first image into content so it doesn't remove another image I have posted in there.</p>
<p>I would like to have the first image in the content removed completely in posts. so that in the future I don't have to insert a featured image into the content every time, just so other images show up when I have more than one image. So far I haven't been able to find anything on this except having to go into 20,000 posts and remove the first image. </p>
<p>Any ideas?</p>
|
[
{
"answer_id": 202082,
"author": "totels",
"author_id": 23446,
"author_profile": "https://wordpress.stackexchange.com/users/23446",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know of any plugin specifically for this, there's nothing in WP that will do this but it's not too difficult to implement with a little php, even 20k posts shouldn't be too extreme. Depending on your server settings you may need to do some workarounds to make sure the connection stays alive but the basic idea would be to loop through all posts, check that it's a proper post (not a page, revision, custom post_type, etc.) and then run a string replace on the content very much like the code you already have.</p>\n\n<p>This is untested, just as an example:\n</p>\n\n<pre><code>$query = new WP_Query( array(\n 'post_type' => 'post',\n 'post_status' => 'publish'\n) );\n\nforeach ( $query->posts as $edit_post ) {\n $edit_post->post_content\n wp_update_post( array(\n 'ID' => $edit_post->ID,\n 'post_content' => preg_replace( \"/<img[^>]+\\>/i\", \"\", $edit_post->post_content, 1 )\n );\n}\n</code></pre>\n\n<p>You'd probably want to put that in a plugin of it's own with some admin page code to run it someplace safe, hopefully you get the idea.</p>\n\n<p><a href=\"http://wp-cli.org/\" rel=\"nofollow\">WP-CLI</a> has the ability to do bulk edits with <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\">search-replace</a> of DB strings and could probably be used to do something similar.</p>\n\n<pre class=\"lang-shell prettyprint-override\"><code>$ wp search-replace '/<img[^>]+\\>/i' '' wp_posts --regex \n</code></pre>\n"
},
{
"answer_id": 256997,
"author": "Vinnie James",
"author_id": 34762,
"author_profile": "https://wordpress.stackexchange.com/users/34762",
"pm_score": 0,
"selected": false,
"text": "<p>You could probably do this on the front end using something like this</p>\n\n<pre><code>$('img ')[0].remove()\n</code></pre>\n"
},
{
"answer_id": 257032,
"author": "Elex",
"author_id": 113687,
"author_profile": "https://wordpress.stackexchange.com/users/113687",
"pm_score": 0,
"selected": false,
"text": "<p>If you only want to hide it, you can do it in CSS.</p>\n\n<pre><code>.your-post-content-class img:first-of-type { display:none; }\n</code></pre>\n\n<p>If you want to really remove if from <code>post_content</code>, you can get the first image tag in your <code>post_content</code> then update it.</p>\n\n<pre><code>function removeFirstImgTag($post_id) {\n $post = get_post($post_id);\n $content = $post->post_content;\n preg_match('<img([\\w\\W]+?)/>', $content, $matches);\n $content = str_replace($matches[0][0], '', $content);\n\n wp_update_post(array(\n 'ID' => $post_id,\n 'post_content' => $content,\n ));\n}\n</code></pre>\n\n<p>You get the post_content without <code>apply_filters('the_content')</code>, then you get the first img tag with regex, then you update it.</p>\n\n<p>I haven't test this yet, but I think, that's works :)</p>\n"
}
] |
2015/09/07
|
[
"https://wordpress.stackexchange.com/questions/201922",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80001/"
] |
I've been using this code:
```
function remove_first_image ($content) {
if (!is_page() && !is_feed() && !is_feed()) {
$content = preg_replace("/<img[^>]+\>/i", "", $content, 1);
} return $content;
}
add_filter('the_content', 'remove_first_image');
```
for a few years now on my site that has almost 20,000 posts with images inserted at the top. I have a plugin that uses the first image as a featured image as well. sometimes I need to still insert a first image into content so it doesn't remove another image I have posted in there.
I would like to have the first image in the content removed completely in posts. so that in the future I don't have to insert a featured image into the content every time, just so other images show up when I have more than one image. So far I haven't been able to find anything on this except having to go into 20,000 posts and remove the first image.
Any ideas?
|
I don't know of any plugin specifically for this, there's nothing in WP that will do this but it's not too difficult to implement with a little php, even 20k posts shouldn't be too extreme. Depending on your server settings you may need to do some workarounds to make sure the connection stays alive but the basic idea would be to loop through all posts, check that it's a proper post (not a page, revision, custom post\_type, etc.) and then run a string replace on the content very much like the code you already have.
This is untested, just as an example:
```
$query = new WP_Query( array(
'post_type' => 'post',
'post_status' => 'publish'
) );
foreach ( $query->posts as $edit_post ) {
$edit_post->post_content
wp_update_post( array(
'ID' => $edit_post->ID,
'post_content' => preg_replace( "/<img[^>]+\>/i", "", $edit_post->post_content, 1 )
);
}
```
You'd probably want to put that in a plugin of it's own with some admin page code to run it someplace safe, hopefully you get the idea.
[WP-CLI](http://wp-cli.org/) has the ability to do bulk edits with [search-replace](http://wp-cli.org/commands/search-replace/) of DB strings and could probably be used to do something similar.
```shell
$ wp search-replace '/<img[^>]+\>/i' '' wp_posts --regex
```
|
201,963 |
<p>I have a form that I created using a plugin which upon clicking the Submit button, it's redirecting to a URL that I selected in the form's settings. But the problem is that any other form that I create, it gets directed to the same URL that I selected on my original form. I need to trace the Submit action to see where its going and what functions are being called.
Any thoughts and suggestions will greatly be appreciated. </p>
|
[
{
"answer_id": 201984,
"author": "dev",
"author_id": 79859,
"author_profile": "https://wordpress.stackexchange.com/users/79859",
"pm_score": 1,
"selected": false,
"text": "<p>yes you can use jquery, like</p>\n\n<pre><code>$('form').attr('action');\n</code></pre>\n"
},
{
"answer_id": 201994,
"author": "Sebastien",
"author_id": 67132,
"author_profile": "https://wordpress.stackexchange.com/users/67132",
"pm_score": 3,
"selected": true,
"text": "<p>Still using jQuery, you can do this:</p>\n\n<pre><code>$('form').submit(function() {\n // Use this to echo in JS console.\n console.log( $(this).attr('action') );\n // Use this to display a popup.\n alert( $(this).attr('action') );\n});\n</code></pre>\n\n<p>This will track <strong>every</strong> form being submitted.</p>\n\n<p>Place this between <code><script></code> tags or in a JS file. Like @dev said, this for debug purpose, don't keep this in your code.</p>\n\n<p>You may have to wait for Document to be ready, then you'd use :</p>\n\n<pre><code>// Needs jQuery too.\n$(function() {\n // Copy code here.\n});\n</code></pre>\n"
}
] |
2015/09/07
|
[
"https://wordpress.stackexchange.com/questions/201963",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58774/"
] |
I have a form that I created using a plugin which upon clicking the Submit button, it's redirecting to a URL that I selected in the form's settings. But the problem is that any other form that I create, it gets directed to the same URL that I selected on my original form. I need to trace the Submit action to see where its going and what functions are being called.
Any thoughts and suggestions will greatly be appreciated.
|
Still using jQuery, you can do this:
```
$('form').submit(function() {
// Use this to echo in JS console.
console.log( $(this).attr('action') );
// Use this to display a popup.
alert( $(this).attr('action') );
});
```
This will track **every** form being submitted.
Place this between `<script>` tags or in a JS file. Like @dev said, this for debug purpose, don't keep this in your code.
You may have to wait for Document to be ready, then you'd use :
```
// Needs jQuery too.
$(function() {
// Copy code here.
});
```
|
201,968 |
<p>My question is: Is it ok, or even preferable, to use html instead of php when possible? </p>
<p>Why I ask:
Wordpress seems to use php even for simple tasks, where old good html would do the job. Php code is <strong>not</strong> famous for its simplicity or readability. Besides this, I guess that all the unnecessary database requests make the serving of the web pages just a bit slower. So I wonder if there is a good reason, I can not think of, that WP prefers to use php instead of html.
Example:</p>
<pre><code><div class="site-info">
<?php do_action( 'twentyfourteen_credits' ); ?>
<a href="<?php echo esc_url( __( 'http://wordpress.org/', 'twentyfourteen' ) ); ?>"><?php printf( __( 'Proudly powered by %s', 'twentyfourteen' ), 'WordPress' ); ?></a>.
Copyright ©<?php echo date( 'Y' ); ?>
</div>
</code></pre>
<p>instead of </p>
<pre><code><div class="site-info">
<a href="http://wordpress.org">Proudly powered by WordPress</a>.
Copyright ©2015
</div>
</code></pre>
<p>(I understand that in the example above, I have to change the year number once per year, and the text can't be translated, but this is IMO an acceptable trade off for nicer, faster code) </p>
|
[
{
"answer_id": 201969,
"author": "Maikal",
"author_id": 38034,
"author_profile": "https://wordpress.stackexchange.com/users/38034",
"pm_score": -1,
"selected": false,
"text": "<p>Well.. it is faster to use strict html, becouse server takes some time to make php functions/actions/code.. but it's less flexable to echo html text than php..</p>\n\n<p>for ex. <code>date( 'Y' )</code> takes only 2.5033950805664<strong>E-5</strong> secconds to echo current date, othere single, not DB functions should take appr. same time to compleat them.</p>\n\n<p>Consider better to use some chaching plugin instead of stripping out php code.</p>\n\n<p><strong>NOTE: you cannot use html instead of php - it's 2 different languages and they surve for different tasks.</strong></p>\n"
},
{
"answer_id": 201989,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Quite strange that the core developers would decide to make an URL translatable, it is actually a case here of over-doing something. But anyways, lets get to the main question</p>\n\n<h2>PHP vs HTML</h2>\n\n<p>Although there are many reasons I can think of why one would prefer PHP above HTML, and that goes for the core developers as well, the main reason lies in one big difference between these two different languages</p>\n\n<ul>\n<li>PHP is dynamic language and HTML is static language</li>\n</ul>\n\n<p>This means that code written in PHP will update itself according to the condition/s set for that specific operation, it does not need human intervention, while anything written in HTML will remain the same until someone manually updates the code to reflect changes, so it requires human intervention. Not having to manually update a single line of code or a thousand lines of code when changes are required is one of the main reasons PHP is used and prefered above a language like HTML</p>\n\n<p>I do think your main issue is that you are still very new to PHP and do not really understand the language as such, which is actually a great opportunity then to dig in PHP and to learn the basics to get you going</p>\n\n<p>As to your exact question, there is nothing wrong swopping PHP with HTML, but you will loose the dynamic aspect of PHP</p>\n"
},
{
"answer_id": 202003,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>The key distinction is that you are looking at the <em>public</em> theme. It's meant to be used by many sites out there and be is accommodating as possible.</p>\n\n<p>It might be <em>your</em> personal choice to edit year in every footer of every site you own, but for someone else that would seem like waste of (costly) human resources on something PHP can do effortlessly and essentially free. If you <em>profile</em> performance of single date call its impact would be incredibly insignificant on resources.</p>\n\n<p>Same story with <em>just</em> \"text can't be translated\" downside. This would be incredibly unfitting for people who <em>do</em> need it translated and costly to <em>make</em> it translatable. If I remember right the amount of non–English WP installs worldwide is now a majority of them.</p>\n"
},
{
"answer_id": 202017,
"author": "Unix",
"author_id": 37313,
"author_profile": "https://wordpress.stackexchange.com/users/37313",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, you can use HTML tags instead of PHP code to print the static content. So it is possible. For example, you may have a website with static content excepting the articles, the comments and an archive page; in that case, you would have the header, the menus, the sidebars, the widgets, the footer and even shortcodes used into an article as static content.</p>\n\n<p>The files will be <code>.php</code> anyway because all the WordPress themes have a PHP structure, so this files need to be interpreted by the server to work. The header content is interpreted from the file <code>header.php</code>, the footer content is interpreted from <code>footer.php</code>, and so on. You can't change the files extension.</p>\n\n<p>Then, if you want to use HTML tags instead of PHP code to have a code «faster», the answer is yes: by reducing the number of database calls you will be able to increase your WordPress speed. Of course.</p>\n\n<p>By the way, the code won't be «nicer». PHP is hard to read if you don't know PHP. (Moreover, HTML is not a programming language, but a markup language. Each one has its functionallity).</p>\n\n<p>PD: There are more efficient and preferable ways to increase the WordPress speed. This is the last method I would use.</p>\n"
}
] |
2015/09/07
|
[
"https://wordpress.stackexchange.com/questions/201968",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80031/"
] |
My question is: Is it ok, or even preferable, to use html instead of php when possible?
Why I ask:
Wordpress seems to use php even for simple tasks, where old good html would do the job. Php code is **not** famous for its simplicity or readability. Besides this, I guess that all the unnecessary database requests make the serving of the web pages just a bit slower. So I wonder if there is a good reason, I can not think of, that WP prefers to use php instead of html.
Example:
```
<div class="site-info">
<?php do_action( 'twentyfourteen_credits' ); ?>
<a href="<?php echo esc_url( __( 'http://wordpress.org/', 'twentyfourteen' ) ); ?>"><?php printf( __( 'Proudly powered by %s', 'twentyfourteen' ), 'WordPress' ); ?></a>.
Copyright ©<?php echo date( 'Y' ); ?>
</div>
```
instead of
```
<div class="site-info">
<a href="http://wordpress.org">Proudly powered by WordPress</a>.
Copyright ©2015
</div>
```
(I understand that in the example above, I have to change the year number once per year, and the text can't be translated, but this is IMO an acceptable trade off for nicer, faster code)
|
Quite strange that the core developers would decide to make an URL translatable, it is actually a case here of over-doing something. But anyways, lets get to the main question
PHP vs HTML
-----------
Although there are many reasons I can think of why one would prefer PHP above HTML, and that goes for the core developers as well, the main reason lies in one big difference between these two different languages
* PHP is dynamic language and HTML is static language
This means that code written in PHP will update itself according to the condition/s set for that specific operation, it does not need human intervention, while anything written in HTML will remain the same until someone manually updates the code to reflect changes, so it requires human intervention. Not having to manually update a single line of code or a thousand lines of code when changes are required is one of the main reasons PHP is used and prefered above a language like HTML
I do think your main issue is that you are still very new to PHP and do not really understand the language as such, which is actually a great opportunity then to dig in PHP and to learn the basics to get you going
As to your exact question, there is nothing wrong swopping PHP with HTML, but you will loose the dynamic aspect of PHP
|
201,976 |
<p>I am trying to get a list of a custom post type's IDs using WP_Query, but it is returning undesired result, which is a memory leak and stuck browser.</p>
<p>Here is the code I use:</p>
<pre><code> $the_query = new WP_Query("post_type=post&posts_per_page=-1&field=ids");
if ($the_query->have_posts()) {
while ($the_query->have_posts()){
echo get_the_ID();
}
}
</code></pre>
<p>It makes my browser infinitely trying to load the page. May be somebody know what's wrong with the code above..</p>
|
[
{
"answer_id": 201978,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>You are missing the <code>the_post()</code> function call in the loop. Just add</p>\n\n<pre><code>$the_query->the_post();\n</code></pre>\n\n<p>in your loop. Apart from that, your loop should work</p>\n\n<h2>EDIT</h2>\n\n<p>You should also not forget to reset your postdata after the query is done</p>\n"
},
{
"answer_id": 201986,
"author": "Marek",
"author_id": 54031,
"author_profile": "https://wordpress.stackexchange.com/users/54031",
"pm_score": 2,
"selected": false,
"text": "<p>I know you want solution \"using WP_Query\", but why not use <code>get_posts()</code> for this? </p>\n\n<pre><code>$posts_ids = get_posts('post_type=post&posts_per_page=-1&fields=ids');\n// $posts_ids is now an array of IDs\necho implode(',', $posts_ids); // prints: 123, 124, 125, 126, ...\n\n// or\n\nforeach( $posts_ids as $id ) {\n echo $id;\n}\n</code></pre>\n"
}
] |
2015/09/08
|
[
"https://wordpress.stackexchange.com/questions/201976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32989/"
] |
I am trying to get a list of a custom post type's IDs using WP\_Query, but it is returning undesired result, which is a memory leak and stuck browser.
Here is the code I use:
```
$the_query = new WP_Query("post_type=post&posts_per_page=-1&field=ids");
if ($the_query->have_posts()) {
while ($the_query->have_posts()){
echo get_the_ID();
}
}
```
It makes my browser infinitely trying to load the page. May be somebody know what's wrong with the code above..
|
You are missing the `the_post()` function call in the loop. Just add
```
$the_query->the_post();
```
in your loop. Apart from that, your loop should work
EDIT
----
You should also not forget to reset your postdata after the query is done
|
201,977 |
<p>I have a shortcode that (among other things) echoes out a menu using <code>wp_nav_menu</code> like so</p>
<pre><code>if ( ! function_exists( 'foundationPress_main_nav' ) ) {
function foundationPress_main_nav() {
wp_nav_menu(array(
'container' => false, // remove nav container
'container_class' => '', // class of container
'menu' => '', // menu name
'menu_class' => '', // adding custom nav class
'theme_location' => 'main-nav', // where it's located in the theme
'before' => '', // before each link <a>
'after' => '', // after each link </a>
'echo' => true,
'link_before' => '', // before each link text
'link_after' => '', // after each link text
'depth' => 2, // limit the depth of the nav
'fallback_cb' => false, // fallback function (see below)
// 'walker' => new FoundationPress_top_bar_walker()
));
}
}
</code></pre>
<p>The menu is registered <code>register_nav_menus(array('main-nav' => 'Main Navigation',));</code> and set up within the Wordpress admin.</p>
<p>Here's where it's behaving oddly: it doesn't render within the element I'm echoing it in.
So for example if the code in the shortcode is something like:</p>
<pre><code><nav>
<?php foundationPress_main_nav(); ?>
</nav>
</code></pre>
<p>Instead of the menu appearing within the <code><nav></code> element <em>(around the middle of the page, below the fold)</em> it appears at the top of the page, and is the first element nested within <code>div.entry-content</code>.</p>
<p><strong>Any ideas why it's sort of hooking to the top of the page this way instead of rendering within the element it's actually nested in?</strong></p>
<p>(I'm using the FoundationPress framework to build the theme and I've made plenty of menus before, not sure if I'm missing something apparent)</p>
<p>For more detail, here's the entire shortcode, although only the last few lines are relevant to the issue:</p>
<pre><code>function rvr_cards_carousel( $atts ) {
$atts = shortcode_atts(
array(
'background' => '',
'load' => '10',
), $atts, 'rvr_cards' );
$args = array(
'post_type' => 'cards',
'posts_per_page' => $atts['load'],
'order' => 'ASC',
);
$cards_query = new WP_Query( $args );
$output = '';
if( $cards_query->have_posts() ) :
if( ! empty( $atts['background'] ) ) {
$output .= '<div class="cards-carousel-container row full-width" style="background: url('.$atts["background"].') no-repeat left top / cover;">';
} else {
$output .= '<div class="cards-carousel-container row full-width">';
}
$output .= '<ul class="cards-carousel" data-equalizer>';
while( $cards_query->have_posts() ) : $cards_query->the_post();
$output .= '<li>';
$output .= '<div class="inner" data-equalizer-watch>';
$output .= get_the_content();
$output .= '<div class="card-divider"></div>';
$output .= '<h6 class="card-author">'.get_the_title().'</h6>';
$output .= '<div class="card-symbol"></div>';
$output .= '</div>';
$output .= '</li>';
endwhile;
endif;
wp_reset_postdata();
$cardnav = "enabled";
$output .= '</ul>';
if ($cardnav = "enabled") {
$output .= '<div class="four columns"></div>';
$output .= '<nav class="contain-to-grid eight columns primary-nav" id="home-card-nav">';
$output .= foundationPress_main_nav();
$output .= '<div id="card-nav-overflow"></div></nav>';
}
$output .= '</div>';
echo $output;
}
add_shortcode( 'rvr_cards', 'rvr_cards_carousel' );
</code></pre>
<p>Here's an image depicting the shortcode, where the menu should be and where it is. You can also <a href="http://goo.gl/zsnSwh" rel="nofollow noreferrer">access the live page here</a>.<a href="https://i.stack.imgur.com/dcAX3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dcAX3.jpg" alt="image of wp nav issue where menu is not contained by parent element"></a></p>
|
[
{
"answer_id": 248806,
"author": "FellowTraveler",
"author_id": 108673,
"author_profile": "https://wordpress.stackexchange.com/users/108673",
"pm_score": 2,
"selected": false,
"text": "<p><code>'echo' => true</code> needs to be <code>'echo' => false</code> in your <code>wp_nav_menu</code> array for it to nest. From the <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\">docs</a> you'll find</p>\n\n<blockquote>\n <p>'echo' (bool) Whether to echo the menu or return it. Default true.</p>\n</blockquote>\n\n<p>so what's happening is the wp_nav_menu isn't being returned but just echoed, so doesn't nest. </p>\n"
},
{
"answer_id": 263239,
"author": "Karol Krzyczkowski",
"author_id": 117394,
"author_profile": "https://wordpress.stackexchange.com/users/117394",
"pm_score": 1,
"selected": false,
"text": "<p>In shortcode use \"return\" instead of \"echo\". </p>\n\n<p>Shortcode with \"echo\" display the content in the moment it's parsed - before the post content, that's why it displays on top.</p>\n\n<p>With \"return\" it will display the menu in the place where shortode is called.</p>\n"
}
] |
2015/09/08
|
[
"https://wordpress.stackexchange.com/questions/201977",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18228/"
] |
I have a shortcode that (among other things) echoes out a menu using `wp_nav_menu` like so
```
if ( ! function_exists( 'foundationPress_main_nav' ) ) {
function foundationPress_main_nav() {
wp_nav_menu(array(
'container' => false, // remove nav container
'container_class' => '', // class of container
'menu' => '', // menu name
'menu_class' => '', // adding custom nav class
'theme_location' => 'main-nav', // where it's located in the theme
'before' => '', // before each link <a>
'after' => '', // after each link </a>
'echo' => true,
'link_before' => '', // before each link text
'link_after' => '', // after each link text
'depth' => 2, // limit the depth of the nav
'fallback_cb' => false, // fallback function (see below)
// 'walker' => new FoundationPress_top_bar_walker()
));
}
}
```
The menu is registered `register_nav_menus(array('main-nav' => 'Main Navigation',));` and set up within the Wordpress admin.
Here's where it's behaving oddly: it doesn't render within the element I'm echoing it in.
So for example if the code in the shortcode is something like:
```
<nav>
<?php foundationPress_main_nav(); ?>
</nav>
```
Instead of the menu appearing within the `<nav>` element *(around the middle of the page, below the fold)* it appears at the top of the page, and is the first element nested within `div.entry-content`.
**Any ideas why it's sort of hooking to the top of the page this way instead of rendering within the element it's actually nested in?**
(I'm using the FoundationPress framework to build the theme and I've made plenty of menus before, not sure if I'm missing something apparent)
For more detail, here's the entire shortcode, although only the last few lines are relevant to the issue:
```
function rvr_cards_carousel( $atts ) {
$atts = shortcode_atts(
array(
'background' => '',
'load' => '10',
), $atts, 'rvr_cards' );
$args = array(
'post_type' => 'cards',
'posts_per_page' => $atts['load'],
'order' => 'ASC',
);
$cards_query = new WP_Query( $args );
$output = '';
if( $cards_query->have_posts() ) :
if( ! empty( $atts['background'] ) ) {
$output .= '<div class="cards-carousel-container row full-width" style="background: url('.$atts["background"].') no-repeat left top / cover;">';
} else {
$output .= '<div class="cards-carousel-container row full-width">';
}
$output .= '<ul class="cards-carousel" data-equalizer>';
while( $cards_query->have_posts() ) : $cards_query->the_post();
$output .= '<li>';
$output .= '<div class="inner" data-equalizer-watch>';
$output .= get_the_content();
$output .= '<div class="card-divider"></div>';
$output .= '<h6 class="card-author">'.get_the_title().'</h6>';
$output .= '<div class="card-symbol"></div>';
$output .= '</div>';
$output .= '</li>';
endwhile;
endif;
wp_reset_postdata();
$cardnav = "enabled";
$output .= '</ul>';
if ($cardnav = "enabled") {
$output .= '<div class="four columns"></div>';
$output .= '<nav class="contain-to-grid eight columns primary-nav" id="home-card-nav">';
$output .= foundationPress_main_nav();
$output .= '<div id="card-nav-overflow"></div></nav>';
}
$output .= '</div>';
echo $output;
}
add_shortcode( 'rvr_cards', 'rvr_cards_carousel' );
```
Here's an image depicting the shortcode, where the menu should be and where it is. You can also [access the live page here](http://goo.gl/zsnSwh).[](https://i.stack.imgur.com/dcAX3.jpg)
|
`'echo' => true` needs to be `'echo' => false` in your `wp_nav_menu` array for it to nest. From the [docs](https://developer.wordpress.org/reference/functions/wp_nav_menu/) you'll find
>
> 'echo' (bool) Whether to echo the menu or return it. Default true.
>
>
>
so what's happening is the wp\_nav\_menu isn't being returned but just echoed, so doesn't nest.
|
202,009 |
<p>Im trying to figure out how can I change names to cookies that wordpress is setting for example on login.</p>
<pre><code>wordpress_test_cookie = sitename_test_cookie
</code></pre>
<p>or/ and</p>
<pre><code> wordpress_logged_in = sitename_test_cookie
</code></pre>
|
[
{
"answer_id": 202019,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<p>Check out the <a href=\"https://developer.wordpress.org/reference/functions/wp_cookie_constants/\" rel=\"noreferrer\"><code>wp_cookie_constants()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/ms_cookie_constants/\" rel=\"noreferrer\"><code>ms_cookie_constants()</code></a> functions, to see available cookies.</p>\n\n<p>We can try this in the <code>wp-config.php</code> file:</p>\n\n<pre><code>// Here we just simulate how it's done in the core\ndefine( 'COOKIEHASH', md5( 'http://example.tld' ) ); \n\n// Then we override the cookie names:\ndefine( 'USER_COOKIE', 'wpse_user_' . COOKIEHASH );\ndefine( 'PASS_COOKIE', 'wpse_pass_' . COOKIEHASH );\ndefine( 'AUTH_COOKIE', 'wpse_' . COOKIEHASH );\ndefine( 'SECURE_AUTH_COOKIE', 'wpse_sec_' . COOKIEHASH );\ndefine( 'LOGGED_IN_COOKIE', 'wpse_logged_in_' . COOKIEHASH );\ndefine( 'TEST_COOKIE', 'wpse_test_cookie' );\n</code></pre>\n\n<p>or using PHP 5.6+ :</p>\n\n<pre><code>// Then we override the cookie names:\nconst USER_COOKIE = 'wpse_user_' . COOKIEHASH;\nconst PASS_COOKIE = 'wpse_pass_' . COOKIEHASH;\nconst AUTH_COOKIE = 'wpse_' . COOKIEHASH;\nconst SECURE_AUTH_COOKIE = 'wpse_sec_' . COOKIEHASH;\nconst LOGGED_IN_COOKIE = 'wpse_logged_in_' . COOKIEHASH;\nconst TEST_COOKIE = 'wpse_test_cookie';\n</code></pre>\n\n<p>where we must adjust the site url <code>http://example.tld</code> to our needs.</p>\n\n<p>But I also wonder, as @PieterGoosen, why you need to change it.</p>\n"
},
{
"answer_id": 275387,
"author": "user1138",
"author_id": 95162,
"author_profile": "https://wordpress.stackexchange.com/users/95162",
"pm_score": 1,
"selected": false,
"text": "<p>To add to the comments... another reason for changing the test cookie in particular is to block bad logins. Ripped straight outta the always excellent ask apache...</p>\n\n<p><a href=\"http://www.askapache.com/security/stop-wordpress-exploits-spam/#Block_Logins_bad_cookie\" rel=\"nofollow noreferrer\">http://www.askapache.com/security/stop-wordpress-exploits-spam/#Block_Logins_bad_cookie</a></p>\n\n<p><strong>Block Logins with bad cookie</strong></p>\n\n<p>You should all be using a custom login cookie name definable with constants in your wp-config.php file. That means the default cookie wordpress_test_cookie will never be set, so you can block bots that use this default!</p>\n\n<p>The way to deviate from the default is to set this constant to anything you want in your wp-config.php</p>\n\n<pre><code>define( 'TEST_COOKIE', 'use_this_cookie_name_instead_of_wordpress_test_cookie' );\n</code></pre>\n\n<p><strong>Block bad test cookies</strong></p>\n\n<pre><code>RewriteCond %{THE_REQUEST} ^POST.*wp-login [NC]\nRewriteCond %{HTTP:Cookie} \"wordpress_test_cookie=WP+Cookie+check\" [NC]\nRewriteRule .* - [F]'\n</code></pre>\n"
}
] |
2015/09/08
|
[
"https://wordpress.stackexchange.com/questions/202009",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80053/"
] |
Im trying to figure out how can I change names to cookies that wordpress is setting for example on login.
```
wordpress_test_cookie = sitename_test_cookie
```
or/ and
```
wordpress_logged_in = sitename_test_cookie
```
|
Check out the [`wp_cookie_constants()`](https://developer.wordpress.org/reference/functions/wp_cookie_constants/) and [`ms_cookie_constants()`](https://developer.wordpress.org/reference/functions/ms_cookie_constants/) functions, to see available cookies.
We can try this in the `wp-config.php` file:
```
// Here we just simulate how it's done in the core
define( 'COOKIEHASH', md5( 'http://example.tld' ) );
// Then we override the cookie names:
define( 'USER_COOKIE', 'wpse_user_' . COOKIEHASH );
define( 'PASS_COOKIE', 'wpse_pass_' . COOKIEHASH );
define( 'AUTH_COOKIE', 'wpse_' . COOKIEHASH );
define( 'SECURE_AUTH_COOKIE', 'wpse_sec_' . COOKIEHASH );
define( 'LOGGED_IN_COOKIE', 'wpse_logged_in_' . COOKIEHASH );
define( 'TEST_COOKIE', 'wpse_test_cookie' );
```
or using PHP 5.6+ :
```
// Then we override the cookie names:
const USER_COOKIE = 'wpse_user_' . COOKIEHASH;
const PASS_COOKIE = 'wpse_pass_' . COOKIEHASH;
const AUTH_COOKIE = 'wpse_' . COOKIEHASH;
const SECURE_AUTH_COOKIE = 'wpse_sec_' . COOKIEHASH;
const LOGGED_IN_COOKIE = 'wpse_logged_in_' . COOKIEHASH;
const TEST_COOKIE = 'wpse_test_cookie';
```
where we must adjust the site url `http://example.tld` to our needs.
But I also wonder, as @PieterGoosen, why you need to change it.
|
202,021 |
<p>There are multiple users who have to post their own post on respective post types (like news, reports etc) with feature image upload, extra file (pdf, txt, excel) upload button from the front end which is approve by the admin from backend.</p>
<p>I have solve for feature image but hanging my mind for file upload from front end for the respective post.</p>
<p>I have upload the file also from backend using metabox but no idea how to make it working from frontend to upload.Any suggestion?</p>
|
[
{
"answer_id": 202056,
"author": "grlwondr",
"author_id": 78669,
"author_profile": "https://wordpress.stackexchange.com/users/78669",
"pm_score": 0,
"selected": false,
"text": "<p>Would this plugin possibly provide what you need? <a href=\"https://wordpress.org/plugins/frontend-uploader/\" rel=\"nofollow noreferrer\">Frontend Uploader</a>.</p>\n\n<blockquote>\n <p>This plugin is a simple way for users to submit content to your site. The plugin uses a set of shortcodes to let you create highly customizable submission forms to your posts and pages. Once the content is submitted, it is held for moderation until you approve it.</p>\n</blockquote>\n"
},
{
"answer_id": 258993,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 1,
"selected": false,
"text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/wp_handle_upload\" rel=\"nofollow noreferrer\"><code>wp_handle_upload</code></a> in a custom function</p>\n\n<pre><code>if ( $_FILES ) {\nupload_user_file($_FILES['test_upload']);\n}\n\n\nif ( ! function_exists( 'upload_user_file' ) ) :\n function upload_user_file( $file = array(), $title = false ) {\n\n require_once ABSPATH.'wp-admin/includes/admin.php';\n\n $file_return = wp_handle_upload($file, array('test_form' => false));\n\n if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){\n\n return false;\n\n }else{\n\n $filename = $file_return['file'];\n\n $attachment = array(\n 'post_mime_type' => $file_return['type'],\n 'post_content' => '',\n 'post_type' => 'attachment',\n 'post_status' => 'inherit',\n 'guid' => $file_return['url']\n );\n\n if($title){\n $attachment['post_title'] = $title;\n }\n\n $attachment_id = wp_insert_attachment( $attachment, $filename );\n\n require_once(ABSPATH . 'wp-admin/includes/image.php');\n\n $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );\n\n wp_update_attachment_metadata( $attachment_id, $attachment_data );\n\n if( 0 < intval( $attachment_id ) ) {\n return $attachment_id;\n }\n }\n\n return false;\n }\nendif;\n</code></pre>\n"
}
] |
2015/09/08
|
[
"https://wordpress.stackexchange.com/questions/202021",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65450/"
] |
There are multiple users who have to post their own post on respective post types (like news, reports etc) with feature image upload, extra file (pdf, txt, excel) upload button from the front end which is approve by the admin from backend.
I have solve for feature image but hanging my mind for file upload from front end for the respective post.
I have upload the file also from backend using metabox but no idea how to make it working from frontend to upload.Any suggestion?
|
Use [`wp_handle_upload`](https://codex.wordpress.org/Function_Reference/wp_handle_upload) in a custom function
```
if ( $_FILES ) {
upload_user_file($_FILES['test_upload']);
}
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
require_once ABSPATH.'wp-admin/includes/admin.php';
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
}else{
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
endif;
```
|
202,022 |
<p>Im looking for a way to add a custom class to the add-to-cart button on the single-product.php page in Woocommerce. I have tried the following without any result:</p>
<ol>
<li>Copy whole woocommerce-folder from the folder "plugins" to "themes/MY-THEME/woocommerce".</li>
<li>Modifying the file "add-to-cart.php" in "themes/MY-THEME/woocommerce/loop/add-to-cart.php</li>
</ol>
<p>
<pre><code>if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
global $product;
echo apply_filters( 'woocommerce_loop_add_to_cart_link',
sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>',
esc_url( $product->add_to_cart_url() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button MY-TEST-CLASS-HERE' : '',
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )
),
$product );
</code></pre>
<p>Allthough I cant see the "MY-TEST-CLASS-HERE" in the source-code. What am I doing wrong?</p>
|
[
{
"answer_id": 202055,
"author": "grlwondr",
"author_id": 78669,
"author_profile": "https://wordpress.stackexchange.com/users/78669",
"pm_score": 0,
"selected": false,
"text": "<p>Are you using a child theme? If not, I would suggest that. Then you can custom style the button in the child theme's \"style.css\" file by editing the style of \"add_to_cart_button\" vs creating a new class</p>\n"
},
{
"answer_id": 202706,
"author": "tao",
"author_id": 45169,
"author_profile": "https://wordpress.stackexchange.com/users/45169",
"pm_score": 3,
"selected": false,
"text": "<p>As explained in <a href=\"http://docs.woothemes.com/document/template-structure/\" rel=\"noreferrer\">their documentation</a> WooCommerce provides a templating structure. Copying WC in your theme won't get you anywhere. </p>\n\n<ol>\n<li>Create a <code>woocommerce</code> folder in your theme.</li>\n<li>Copy any template inside the <code>templates</code> folder of WC inside your <code>woocommerce</code> theme folder. Beware you need to keep the structure from <code>templates</code> folder intact in your <code>woocommerce</code> theme folder for this to work.</li>\n<li>Modify the templates in your theme's <code>woocommerce</code> folder to your liking. They have loading precendence over the ones inside plugin's <code>templates</code>. </li>\n</ol>\n\n<p>Tip: do not copy all the templates from the plugin inside your theme! Only the ones you want to modify. From time to time WC updates their templates and adds functionality. WooCommerce will also let you know when a template you keep in your theme might have an upgraded version inside the plugin, after an upgrade.</p>\n\n<p>And by the way, I suspect the downvote was not for the question itself, but for the title. I bet you know how to add a class to a button. What you didn't know was how to use the templating system of WooCommerce. Because you didn't google it, which I think you (technically) know how to do. Please, pardon my touch of sarcasm, it was either that or another downvote.</p>\n"
},
{
"answer_id": 209615,
"author": "drjorgepolanco",
"author_id": 80074,
"author_profile": "https://wordpress.stackexchange.com/users/80074",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way I found (a little hacky) is wrap the button in a span tag, add the class to the span and then in your css apply the properties to the button inheriting from the span:</p>\n\n<pre><code><span class=\"my-nice-class\">\n <?php woocommerce_get_template( 'loop/add-to-cart.php' ); ?>\n</span>\n</code></pre>\n\n<p>and then in css:</p>\n\n<pre><code>.my-nice-class .button {\n color: black;\n}\n</code></pre>\n"
}
] |
2015/09/08
|
[
"https://wordpress.stackexchange.com/questions/202022",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40381/"
] |
Im looking for a way to add a custom class to the add-to-cart button on the single-product.php page in Woocommerce. I have tried the following without any result:
1. Copy whole woocommerce-folder from the folder "plugins" to "themes/MY-THEME/woocommerce".
2. Modifying the file "add-to-cart.php" in "themes/MY-THEME/woocommerce/loop/add-to-cart.php
```
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
global $product;
echo apply_filters( 'woocommerce_loop_add_to_cart_link',
sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>',
esc_url( $product->add_to_cart_url() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button MY-TEST-CLASS-HERE' : '',
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )
),
$product );
```
Allthough I cant see the "MY-TEST-CLASS-HERE" in the source-code. What am I doing wrong?
|
As explained in [their documentation](http://docs.woothemes.com/document/template-structure/) WooCommerce provides a templating structure. Copying WC in your theme won't get you anywhere.
1. Create a `woocommerce` folder in your theme.
2. Copy any template inside the `templates` folder of WC inside your `woocommerce` theme folder. Beware you need to keep the structure from `templates` folder intact in your `woocommerce` theme folder for this to work.
3. Modify the templates in your theme's `woocommerce` folder to your liking. They have loading precendence over the ones inside plugin's `templates`.
Tip: do not copy all the templates from the plugin inside your theme! Only the ones you want to modify. From time to time WC updates their templates and adds functionality. WooCommerce will also let you know when a template you keep in your theme might have an upgraded version inside the plugin, after an upgrade.
And by the way, I suspect the downvote was not for the question itself, but for the title. I bet you know how to add a class to a button. What you didn't know was how to use the templating system of WooCommerce. Because you didn't google it, which I think you (technically) know how to do. Please, pardon my touch of sarcasm, it was either that or another downvote.
|
202,076 |
<p>I'm using the <a href="https://wordpress.org/plugins/redirection/" rel="noreferrer">Redirection plugin</a>. It enables a 'Redirection' submenu under "Tools" menu in Admin panel. As an Administrator I can access the plugin. But I want to avail it for my 'editor' accounts too.</p>
<p>I've searched a lot, but found solution like <a href="http://develop.serialdesigngroup.com/wordpress/redirection-plugin-editor-role-access" rel="noreferrer">this</a> that are offering solution like editing the plugin itself. I actually don't want to edit plugin files directly, as on next update all the changes will wipe out.</p>
<p>So, how can I let the 'editor' get access to the 'Redirection' submenu under 'Tools' menu?</p>
|
[
{
"answer_id": 202077,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 5,
"selected": true,
"text": "<h1>Update 2020</h1>\n<p>The original answer was of 2015, and the author has no affiliation with the plugin, so not aware of any changes to the plugin at all. You are requested to follow any updated helpful answer that might help you on this issue.</p>\n<h1>Original Answer</h1>\n<p>Good news is, from version 2.3.7 of Redirection plugin, they introduced a filter called <code>redirection_role</code> for the privilege. Here's is the <a href=\"http://plugins.svn.wordpress.org/redirection/tags/2.3.5/redirection.php\" rel=\"nofollow noreferrer\">core code</a> (v.2.3.7):</p>\n<pre><code>add_management_page( __( "Redirection", 'redirection' ), __( "Redirection", 'redirection' ), apply_filters( 'redirection_role', 'administrator' ), basename( __FILE__ ), array( &$this, "admin_screen" ) );\n</code></pre>\n<p>###Solution\nJust put the following code into your theme's <code>functions.php</code> to enable 'editor' to get access to the 'Redirection' submenu:</p>\n<pre><code>/**\n * Redirection Plugin Editor access\n */\nadd_filter( 'redirection_role', 'redirection_to_editor' );\nfunction redirection_to_editor() {\n return 'edit_pages';\n}\n</code></pre>\n<p>See <a href=\"https://codex.wordpress.org/Roles_and_Capabilities#Editor\" rel=\"nofollow noreferrer\">Editor user role and capabilities in WordPress</a> - WordPress Codex</p>\n"
},
{
"answer_id": 316538,
"author": "Keith Taylor",
"author_id": 7192,
"author_profile": "https://wordpress.stackexchange.com/users/7192",
"pm_score": 1,
"selected": false,
"text": "<p>The answer from @mayeenul-islam is very useful but I don't have enough rep points to vote or comment on it.</p>\n\n<p>Since that answer was published, the Redirection plugin uses REST-API and this can give permission errors even though the function allows access to Editors.</p>\n\n<p>In my case, using Redirection version 3.5, I solved the problem by changing the REST-API setting in the Redirection Options from 'Default /wp-json' to 'Proxy over Admin AJAX'.</p>\n"
}
] |
2015/09/08
|
[
"https://wordpress.stackexchange.com/questions/202076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22728/"
] |
I'm using the [Redirection plugin](https://wordpress.org/plugins/redirection/). It enables a 'Redirection' submenu under "Tools" menu in Admin panel. As an Administrator I can access the plugin. But I want to avail it for my 'editor' accounts too.
I've searched a lot, but found solution like [this](http://develop.serialdesigngroup.com/wordpress/redirection-plugin-editor-role-access) that are offering solution like editing the plugin itself. I actually don't want to edit plugin files directly, as on next update all the changes will wipe out.
So, how can I let the 'editor' get access to the 'Redirection' submenu under 'Tools' menu?
|
Update 2020
===========
The original answer was of 2015, and the author has no affiliation with the plugin, so not aware of any changes to the plugin at all. You are requested to follow any updated helpful answer that might help you on this issue.
Original Answer
===============
Good news is, from version 2.3.7 of Redirection plugin, they introduced a filter called `redirection_role` for the privilege. Here's is the [core code](http://plugins.svn.wordpress.org/redirection/tags/2.3.5/redirection.php) (v.2.3.7):
```
add_management_page( __( "Redirection", 'redirection' ), __( "Redirection", 'redirection' ), apply_filters( 'redirection_role', 'administrator' ), basename( __FILE__ ), array( &$this, "admin_screen" ) );
```
###Solution
Just put the following code into your theme's `functions.php` to enable 'editor' to get access to the 'Redirection' submenu:
```
/**
* Redirection Plugin Editor access
*/
add_filter( 'redirection_role', 'redirection_to_editor' );
function redirection_to_editor() {
return 'edit_pages';
}
```
See [Editor user role and capabilities in WordPress](https://codex.wordpress.org/Roles_and_Capabilities#Editor) - WordPress Codex
|
202,083 |
<p>I'd like to replace all <code>{POST_NAME}</code> 's from my text-widgets on <code>single.php</code> sidebar. I'm thinking of something like this</p>
<pre><code>global $post;
$POST_NAME= $post->post_name;
$sidebar = preg_replace('/\{(POST_NAME)\}/e', "$$1", $sidebar);
</code></pre>
<p>How can I get sidebar HTML into <code>\$sidebar</code></p>
|
[
{
"answer_id": 202089,
"author": "totels",
"author_id": 23446,
"author_profile": "https://wordpress.stackexchange.com/users/23446",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think there's a particularly good way to do this universally. You can use the <a href=\"https://developer.wordpress.org/reference/classes/wp_widget/\" rel=\"nofollow\"><code>widget_display_callback</code></a> filter to modify a widget instance before it is output, but this can be overridden by widgets. You could go through all the widgets and replace their callbacks with a wrapper of your own. But editing the instance won't guarantee you have access to the output as expected.</p>\n\n<p>The only way I can think to guarantee it is to buffer and capture the output of <code>dynamic_sidebar</code> do your string replacement and print out the modified string.</p>\n\n<pre><code>ob_start();\ndynamic_sidebar( 'sidebar' );\n$sidebar_string = ob_get_contents();\nob_end_clean();\necho str_replace( '{POST_NAME}', $post->post_name, $sidebar_string );\n</code></pre>\n"
},
{
"answer_id": 202090,
"author": "Ignat B.",
"author_id": 38121,
"author_profile": "https://wordpress.stackexchange.com/users/38121",
"pm_score": 1,
"selected": true,
"text": "<p>Your code looks well and considerations are correct. In order to achieve your goal, I'd collect HTML and wrap it up like this:</p>\n\n<p>Instead of calling <code><?php dynamic_sidebar($sidebar_id); ?></code> use <code><?php dynamic_sidebar_replaced($sidebar_id); ?></code> with a function (add it to functions.php) below:</p>\n\n<pre><code>function dynamic_sidebar_replaced($sidebar_id) {\n if (is_single()) { // Optionally, to ensure you're at the single post template.\n\n ob_start(); // Start gathering output\n dynamic_sidebar($sidebar_id);\n global $post;\n $POST_NAME = $post->post_name;\n $sidebar = preg_replace('/\\{(POST_NAME)\\}/e', \"$$1\", $sidebar);\n ob_end_clean();\n\n echo $sidebar;\n return '';\n }\n dynamic_sidebar($sidebar_id);\n}\n</code></pre>\n"
}
] |
2015/09/08
|
[
"https://wordpress.stackexchange.com/questions/202083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78799/"
] |
I'd like to replace all `{POST_NAME}` 's from my text-widgets on `single.php` sidebar. I'm thinking of something like this
```
global $post;
$POST_NAME= $post->post_name;
$sidebar = preg_replace('/\{(POST_NAME)\}/e', "$$1", $sidebar);
```
How can I get sidebar HTML into `\$sidebar`
|
Your code looks well and considerations are correct. In order to achieve your goal, I'd collect HTML and wrap it up like this:
Instead of calling `<?php dynamic_sidebar($sidebar_id); ?>` use `<?php dynamic_sidebar_replaced($sidebar_id); ?>` with a function (add it to functions.php) below:
```
function dynamic_sidebar_replaced($sidebar_id) {
if (is_single()) { // Optionally, to ensure you're at the single post template.
ob_start(); // Start gathering output
dynamic_sidebar($sidebar_id);
global $post;
$POST_NAME = $post->post_name;
$sidebar = preg_replace('/\{(POST_NAME)\}/e', "$$1", $sidebar);
ob_end_clean();
echo $sidebar;
return '';
}
dynamic_sidebar($sidebar_id);
}
```
|
202,097 |
<p><strong>{This question is marked as duplicate but i think my question and answer to it is much simpler then the original one}</strong></p>
<p>Hi i have this following code that is showing before the widget title. For what i understand from my research is that i have to use return, but its not working. Please help.</p>
<pre><code> <?php
function get_review_code(){
echo '<div class="review-slider-wrap">';
echo '<ul class="review-slider">';
global $post;
$args = array( 'numberposts' => 10, 'category_name' => 'review' );
$posts = get_posts( $args );
foreach( $posts as $post ): setup_postdata($post);
echo '<li>';
echo '<div class="white-curve">';
echo the_excerpt();
$author_id=$post->post_author;
echo '<div class="author_full_name">';
echo '- ';
echo the_author_meta('first_name'); echo '&nbsp;';
echo the_author_meta('last_name');
echo '</div>';
echo '</div>';
echo get_avatar( $post->post_author, 230 );
echo '</li>';
endforeach;
echo '</ul>';
echo '</div>';
}
add_shortcode('review_review', 'get_review_code');
</code></pre>
|
[
{
"answer_id": 202098,
"author": "Jorge Y. C. Rodriguez",
"author_id": 35073,
"author_profile": "https://wordpress.stackexchange.com/users/35073",
"pm_score": 0,
"selected": false,
"text": "<p>shortcut should return a value, if you echo it, this will place it before anything else. try this: (not tested)</p>\n\n<pre><code><?php\nfunction get_review_code(){ \n global $post;\n $content = \"\";\n $content .= '<div class=\"review-slider-wrap\">'; \n $content .= '<ul class=\"review-slider\">'; \n $args = array( 'numberposts' => 10, 'category_name' => 'review' );\n $posts = get_posts( $args );\n foreach( $posts as $post ): setup_postdata($post);\n $content .= '<li>'; \n $content .= '<div class=\"white-curve\">'; \n $content .= get_the_excerpt(); \n $author_id = $post->post_author; \n $content .= '<div class=\"author_full_name\">';\n $content .= '- ';\n $content .= get_the_author_meta('first_name');\n $content .= '&nbsp;';\n $content .= get_the_author_meta('last_name');\n $content .= '</div>';\n $content .= '</div>'; \n $content .= get_avatar( $post->post_author, 230 );\n $content .= '</li>';\n endforeach;\n $content .= '</ul>';\n $content .= '</div>';\n return $content;\n}\nadd_shortcode('review_review', 'get_review_code'); \n\n?>\n</code></pre>\n"
},
{
"answer_id": 202099,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 2,
"selected": true,
"text": "<p>Some of the calls in your function will echo rather than return. \nInstead of <a href=\"https://codex.wordpress.org/Function_Reference/the_author_meta\" rel=\"nofollow\">the_author_meta</a>, use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_author_meta\" rel=\"nofollow\">get_the_author_meta</a>.\nInstead of <a href=\"https://codex.wordpress.org/Function_Reference/the_excerpt\" rel=\"nofollow\">the_excerpt</a>, use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_excerpt\" rel=\"nofollow\">get_the_excerpt</a>.\nAnd use jycr753's approach; return the whole string rather than echo it. </p>\n"
}
] |
2015/09/08
|
[
"https://wordpress.stackexchange.com/questions/202097",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78475/"
] |
**{This question is marked as duplicate but i think my question and answer to it is much simpler then the original one}**
Hi i have this following code that is showing before the widget title. For what i understand from my research is that i have to use return, but its not working. Please help.
```
<?php
function get_review_code(){
echo '<div class="review-slider-wrap">';
echo '<ul class="review-slider">';
global $post;
$args = array( 'numberposts' => 10, 'category_name' => 'review' );
$posts = get_posts( $args );
foreach( $posts as $post ): setup_postdata($post);
echo '<li>';
echo '<div class="white-curve">';
echo the_excerpt();
$author_id=$post->post_author;
echo '<div class="author_full_name">';
echo '- ';
echo the_author_meta('first_name'); echo ' ';
echo the_author_meta('last_name');
echo '</div>';
echo '</div>';
echo get_avatar( $post->post_author, 230 );
echo '</li>';
endforeach;
echo '</ul>';
echo '</div>';
}
add_shortcode('review_review', 'get_review_code');
```
|
Some of the calls in your function will echo rather than return.
Instead of [the\_author\_meta](https://codex.wordpress.org/Function_Reference/the_author_meta), use [get\_the\_author\_meta](https://codex.wordpress.org/Function_Reference/get_the_author_meta).
Instead of [the\_excerpt](https://codex.wordpress.org/Function_Reference/the_excerpt), use [get\_the\_excerpt](https://codex.wordpress.org/Function_Reference/get_the_excerpt).
And use jycr753's approach; return the whole string rather than echo it.
|
202,107 |
<p>Is it possible to change the background color of every post based on its category? </p>
<p>I have tried -</p>
<pre><code>body.term-adb {
background-color: #000;
</code></pre>
<p>but this only changes the category page, not the individual posts backgrounds tagged with that category.</p>
<p>Where am I going wrong?</p>
<p>Here is the <a href="http://tinyurl.com/oztp4uf" rel="nofollow">page</a> I'm currently working on</p>
|
[
{
"answer_id": 202108,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 0,
"selected": false,
"text": "<p>Sure that is possible. Take a look at the output of </p>\n\n<pre><code><body <?php body_class( $additional_classes ); ?>>\n</code></pre>\n\n<p>You get a bunch of taxonomy related classes there:</p>\n\n<ul>\n<li><code>tax-portfolio_category</code> << <code>tax-{$taxonomy_name}</code></li>\n<li><code>term-adb</code> << <code>term-{$term_name}</code></li>\n<li><code>term-22</code> << <code>term-{$term_id}</code></li>\n</ul>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 202110,
"author": "Curtis",
"author_id": 78828,
"author_profile": "https://wordpress.stackexchange.com/users/78828",
"pm_score": 2,
"selected": false,
"text": "<p>The body_class() is what controls those classes, and does not include the category in single posts. That is why the CSS doesn't work once you click through to a post.</p>\n\n<p>I did find a function that may help, though. Try placing this in your functions.php. This will add the current post's category back to the body class. You should be able to style your pages easier once the class is available. Double the classes on the body tag if it's still not working, and make sure it matches your CSS.</p>\n\n<pre><code>add_filter('body_class','add_category_to_single');\nfunction add_category_to_single($classes) {\n if (is_single() ) {\n global $post;\n foreach((get_the_category($post->ID)) as $category) {\n $classes[] = 'category-'.$category->slug;\n }\n }\n return $classes;\n}\n</code></pre>\n\n<p><strong>References:</strong></p>\n\n<ol>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/body_class\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/body_class</a></li>\n</ol>\n"
},
{
"answer_id": 401223,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 0,
"selected": false,
"text": "<p>The post class includes the category so you can use that or add it again using the post_class filter</p>\n<pre><code>$terms = wp_get_post_terms( get_the_ID(), 'category', array( 'fields' => 'slugs' ) );\n \n$category_slug = implode(' ', $terms);\n\n$attributes['class'] .= ' '. $category_slug;\n \nreturn $attributes;\n</code></pre>\n"
}
] |
2015/09/08
|
[
"https://wordpress.stackexchange.com/questions/202107",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48140/"
] |
Is it possible to change the background color of every post based on its category?
I have tried -
```
body.term-adb {
background-color: #000;
```
but this only changes the category page, not the individual posts backgrounds tagged with that category.
Where am I going wrong?
Here is the [page](http://tinyurl.com/oztp4uf) I'm currently working on
|
The body\_class() is what controls those classes, and does not include the category in single posts. That is why the CSS doesn't work once you click through to a post.
I did find a function that may help, though. Try placing this in your functions.php. This will add the current post's category back to the body class. You should be able to style your pages easier once the class is available. Double the classes on the body tag if it's still not working, and make sure it matches your CSS.
```
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes) {
if (is_single() ) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
$classes[] = 'category-'.$category->slug;
}
}
return $classes;
}
```
**References:**
1. <https://codex.wordpress.org/Function_Reference/body_class>
|
202,113 |
<p>I have problem with sort posts according to date:</p>
<p>My code now:</p>
<pre><code><?php
global $switched;
$original_blog_id = get_current_blog_id(); // get current blog
$blog_ids = array(4,1);
foreach( $blog_ids as $blog_id ){
switch_to_blog( $blog_id );
$args = array( 'posts_per_page' => 10, 'orderby' => 'date', 'order' => 'DESC');
$myposts = get_posts( $args );
foreach ( $myposts as $post ):
setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach;
wp_reset_postdata();
switch_to_blog( $original_blog_id ); //switched back to current blog
restore_current_blog();
}
?>
</code></pre>
<p>My problem: </p>
<p><a href="http://images.tinypic.pl/i/00700/vracxlcdm296.png" rel="nofollow">http://images.tinypic.pl/i/00700/vracxlcdm296.png</a></p>
<p>I would like:</p>
<p><a href="http://images.tinypic.pl/i/00700/jo2yp8f83bce.png" rel="nofollow">http://images.tinypic.pl/i/00700/jo2yp8f83bce.png</a></p>
<p>I want to sort by date of all blogs.
Not everyone separately.</p>
|
[
{
"answer_id": 202148,
"author": "Dips Kakadiya",
"author_id": 57167,
"author_profile": "https://wordpress.stackexchange.com/users/57167",
"pm_score": 0,
"selected": false,
"text": "<p>You can add argument as below for <code>get_posts</code> method</p>\n\n<pre><code>'orderby' => 'date',\n'order' => 'DESC',\n</code></pre>\n\n<p>For more help please visite below link \n<a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow\">https://codex.wordpress.org/Template_Tags/get_posts</a></p>\n"
},
{
"answer_id": 202311,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 1,
"selected": false,
"text": "<p>Here's how I'd attack your problem (in fact I think I've written code like this in the past, but I can't find it at the moment):</p>\n\n<pre><code>$blogs = array( 4, 1 );\n$all_posts = array();\nforeach( $blogs as $blog ) {\n switch_to_blog( $blog );\n $args = array( 'posts_per_page' => 10, 'orderby' => 'date', 'order' => 'DESC');\n $blog_posts = get_posts( $args );\n foreach( $blog_posts as $blog_post ) {\n // Add the correct permalink to the Post object\n $blog_post->permalink = get_the_permalink( $blog_post->ID );\n $all_posts[] = $blog_post;\n }\n restore_current_blog();\n}\n\nusort( $all_posts, '__sort_by_date' );\n\n// Now you can display all your posts\n\nforeach( $all_posts as $post ) {\n setup_postdata( $post );\n the_title( '<a href=\"' . $post->permalink . '\">', '</a>' );\n}\n\n\nfunction __sort_by_date( $a, $b ) {\n $a_date = strtotime( $a->post_date );\n $b_date = strtotime( $b->post_date );\n if( $a_date === $b_date ) { return 0; }\n if( $a_date > $b_date ) { return 1; }\n return -1;\n}\n</code></pre>\n\n<p><strong>Note:</strong> I've updated the code to get the correct permalink for each post while we're in the proper site (per your comment/answer below).</p>\n\n<h2>References</h2>\n\n<ul>\n<li><a href=\"https://php.net/usort\" rel=\"nofollow\"><code>usort()</code></a></li>\n<li><a href=\"https://php.net/strtotime\" rel=\"nofollow\"><code>strtotime()</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/the_title/\" rel=\"nofollow\"><code>the_title()</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_the_permalink/\" rel=\"nofollow\"><code>get_the_permalink()</code></a></li>\n</ul>\n"
}
] |
2015/09/08
|
[
"https://wordpress.stackexchange.com/questions/202113",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78540/"
] |
I have problem with sort posts according to date:
My code now:
```
<?php
global $switched;
$original_blog_id = get_current_blog_id(); // get current blog
$blog_ids = array(4,1);
foreach( $blog_ids as $blog_id ){
switch_to_blog( $blog_id );
$args = array( 'posts_per_page' => 10, 'orderby' => 'date', 'order' => 'DESC');
$myposts = get_posts( $args );
foreach ( $myposts as $post ):
setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach;
wp_reset_postdata();
switch_to_blog( $original_blog_id ); //switched back to current blog
restore_current_blog();
}
?>
```
My problem:
<http://images.tinypic.pl/i/00700/vracxlcdm296.png>
I would like:
<http://images.tinypic.pl/i/00700/jo2yp8f83bce.png>
I want to sort by date of all blogs.
Not everyone separately.
|
Here's how I'd attack your problem (in fact I think I've written code like this in the past, but I can't find it at the moment):
```
$blogs = array( 4, 1 );
$all_posts = array();
foreach( $blogs as $blog ) {
switch_to_blog( $blog );
$args = array( 'posts_per_page' => 10, 'orderby' => 'date', 'order' => 'DESC');
$blog_posts = get_posts( $args );
foreach( $blog_posts as $blog_post ) {
// Add the correct permalink to the Post object
$blog_post->permalink = get_the_permalink( $blog_post->ID );
$all_posts[] = $blog_post;
}
restore_current_blog();
}
usort( $all_posts, '__sort_by_date' );
// Now you can display all your posts
foreach( $all_posts as $post ) {
setup_postdata( $post );
the_title( '<a href="' . $post->permalink . '">', '</a>' );
}
function __sort_by_date( $a, $b ) {
$a_date = strtotime( $a->post_date );
$b_date = strtotime( $b->post_date );
if( $a_date === $b_date ) { return 0; }
if( $a_date > $b_date ) { return 1; }
return -1;
}
```
**Note:** I've updated the code to get the correct permalink for each post while we're in the proper site (per your comment/answer below).
References
----------
* [`usort()`](https://php.net/usort)
* [`strtotime()`](https://php.net/strtotime)
* [`the_title()`](https://developer.wordpress.org/reference/functions/the_title/)
* [`get_the_permalink()`](https://developer.wordpress.org/reference/functions/get_the_permalink/)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.